boosttypedefboost-mplc++

generic cout that can be wcout depending upon typedef


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


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;