I wanted to create a method to add color to console output that would work in a similar way to std::left
and std::setw()
. I ended up with the code below, and it works exactly how I want it to. I understand how it works, but I would like some clarification on something.
Here is the code:
#include <iostream>
#include <Windows.h>
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
enum class color { blue = FOREGROUND_BLUE, green, cyan, red, purple, yellow, white, bright = FOREGROUND_INTENSITY };
class coutColor {
public:
WORD Color;
coutColor(color colorvalue) : Color((WORD)colorvalue) { }
~coutColor() { SetConsoleTextAttribute(hConsole, (WORD)7); }
};
std::ostream& operator<<(std::ostream& os, const coutColor& colorout) {
SetConsoleTextAttribute(hConsole, colorout.Color);
return os;
}
int main() {
std::cout << coutColor(color::green) << "This text is green!\n";
std::cout << color::red << "This text is red! " << 31 << "\n";
return 0;
}
I understand how coutColor(color::green)
works in the cout
in main()
, but why does just color::red
by itself work as well?
I stumbled upon it by accident while testing different things.
How can it take the enum
type color
as an input, since it's not in the input parameters of the overloaded operator<<
?
Why does it do the same thing as inputting coutColor(color::red)
?