C ++ overload output statement

I have a header file that looks like this:

#pragma once //C++ Output Streams #include <iostream> namespace microtask { namespace log { /** * Severity level. */ enum severity { debug, info, warning, error, critical }; /** * Output the severity level. */ std::ostream& operator<<(std::ostream& out, const severity& level); } } 

and the source file, which looks like this:

 //Definitions #include "severity.hpp" //Namespaces using namespace std; using namespace microtask::log; std::ostream& operator<<(std::ostream& out, const severity& level) { switch(level) { case debug: out << "debug"; break; case info: out << "info"; break; case warning: out << "warning"; break; case error: out << "error"; break; case critical: out << "critical"; break; default: out << "unknown"; break; } return out; } 

which I am trying to compile into a dynamic library. Unfortunately, this error message failed to communicate:

 undefined reference to `microtask::log::operator<<(std::basic_ostream<char, std::char_traits<char> >&, microtask::log::severity const&)' 

What am I doing wrong? I checked other stackoverflow.com questions that seemed similar, but as far as I can tell, I have a format for the operator to overload correctly.

+4
source share
1 answer

In your .cpp file, do not specify using , but instead declare the correct namespace:

 namespace microtask { namespace log { ::std::ostream & operator<<(::std::ostream& out, const severity& level) { // ... } } } 

In fact, don't use using carelessly at all if you can help him. In my opinion, it should be reserved for explicitly specifying the base element and ADL queries.

+3
source

All Articles