Description
I'm overriding << operator
for std::ostream
to ease object display in my code.
I use differents namespaces where I define types of object to display.
That leads me to a compilation error. I have found a fix. It seems that overriding must be declare in a global scope but I really don't understand why. Can someone explain what cause the error ?
Error
main.cpp:22:38: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream’ and ‘std::vector’)
std::cout <<"printVector = " << data << std::endl;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~
Sample code (don't compile)
Here is a dummy exemple to show the error.
#include <iostream>
#include <vector>
inline std::ostream&
operator<<(std::ostream& strm, std::vector<uint8_t>& buffer)
{
return strm << "display std::vector<uint8_t>";
}
namespace aNamespace {
enum TestEnum { a, b, c };
inline std::ostream&
operator<<(std::ostream& strm, TestEnum& value)
{
return strm << "display TestEnum";
}
static void printVector ()
{
std::vector<uint8_t> data {1, 12, 56, 241, 128};
std::cout <<"printVector = " << data << std::endl;
}
}
int main()
{
aNamespace::printVector();
return 0;
}
Environnement
C++11; GCC; Linux
Sample code fix (edited)
Here is a fix version of code for those who are interresed.
#include <iostream>
#include <vector>
inline std::ostream&
operator<<(std::ostream& strm, std::vector<uint8_t>& buffer)
{
return strm << "display std::vector<uint8_t>";
}
namespace aNamespace {
using ::operator<<;
enum class TestEnum { a, b, c };
inline std::ostream&
operator<<(std::ostream& strm, TestEnum value)
{
return strm << "display TestEnum";
}
static void printVector ()
{
std::vector<uint8_t> data {1, 12, 56, 241, 128};
std::cout <<"printVector = " << data << std::endl;
}
}
int main()
{
aNamespace::printVector();
return 0;
}