I’m trying to create a class like std::cout, however, with colored output. The idea is to call colorstream, but when I overload the operator << gives error.
Codes below:
main.cpp
#include <colorstream/colorstream.hpp>
int main ( int argc, char **argv )
{
cpk::colorstream test;
test << "Hello World";
return 0;
}
colorstream/colorstream.hpp
#include <string>
#ifndef CPK_COLORSTREAM_HPP
#define CPK_COLORSTREAM_HPP
namespace cpk
{
class colorstream
{
public:
colorstream ( ) { };
colorstream operator<<( std::string n );
};
}
#endif // #ifndef CPK_COLORSTREAM_HPP
colorstream/colorstream.cpp
#include <string>
#include <iostream>
/**
* CPK Color Stream Header
*/
#include <colorstream/colorstream.hpp>
cpk::colorstream::colorstream operator<<( std::string n )
{
std::cout << n << std::endl;
}
This is the first time I’m trying to overload operators in, so please help me and if I can explain my mistake.
Thank you, Bruno Alano
@edit
The error:
CMakeFiles/cpk.dir/source/cpk.cpp.o: In function `main':
cpk.cpp:(.text+0x45): undefined reference to `cpk::colorstream::operator<<(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: ld returned 1 exit status
make[2]: ** [cpk] Erro 1
make[1]: ** [CMakeFiles/cpk.dir/all] Erro 2
make: ** [all] Erro 2
Well, the error is that you’re definition of the operator is garbled. It should be
cpk::colorstream cpk::colorstream::operator<< (std::string n)
That said, I strong recommend not to pursue this approach further! To create custom streams you want to derive from
std::streambufand override the relevant operations there (e.g.overflow()and, possibly,xsputn()for output streams).Actually, if you want to change color e.g. using ANSI Escape Codes you can just create suitable color manipulators and use them with an
std::ostream:On non-UNIX platforms some other mechanism might be necessary, though…