Question

I've a typedef char char_t which can also be typedef wchar_t char_t and What I want is a generic cout.
I have a util namespace I want an util::cout that would be std::cout if char_t is char and std::wcout if char_t is wchar_t

Was it helpful?

Solution

Yes, no problem; you can do this with a template specialisation holding a static reference to the appropriate object.

template<typename T> struct select_cout;

template<> struct select_cout<char> { static std::ostream &cout; };
std::ostream &select_cout<char>::cout = std::cout;

template<> struct select_cout<wchar_t> { static std::wostream &cout; };
std::wostream &select_cout<wchar_t>::cout = std::wcout;

std::basic_ostream<char_t> &cout = select_cout<char_t>::cout;

OTHER TIPS

You're reinventing a terrible (at least in the here and now, perhaps it was a good decision at one point) design by MS.

Note that every other platform most likely uses UTF-8 for output, so a UTF-8 string through std::cout outputs just fine. On windows, Unicode output on the console is impossible to get right anyway (due to fonts and broken console codepages).

In short, there is no reason to want such a thing, and you're better off using one or the other, not both.

If you are reading files in wide format and using a multibyte program which i picked up from the comments, a solution could be . . .

You can read the file content as a std::wstring in to your programs memory and the use wcstombs_s() to convert the string read from the file in to a multi-byte character string.

Essentially it doesn't matter which format the string is you can always change it when and where needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top