Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I choose between `std::cout` and `std::wcout` according to the defined string type?

I defined my own string type in the code.

typedef wchar_t CharType;
typedef std::basic_string<CharType> StringType;

I have a static class (it won't have an instance) which will print string messages on the screen. I decided to put a COUT static member which will refer to std::cout or std::wcout according to the string type I defined.

Header:

#include <ostream>

class MyTestClass
{
    public:
        // ...
        static std::basic_ostream<CharType> & COUT;
        // ...
}

CPP:

std::basic_ostream<CharType> & MyTestClass::COUT = /* How do I initialize this? */;

Is there a way of initializing this static member COUT?

like image 423
hkBattousai Avatar asked Dec 05 '25 14:12

hkBattousai


2 Answers

This is an option in C++17:

#include <iostream>
#include <type_traits>

template <class T>
auto &get_cout() {
    if constexpr(std::is_same_v<T, char>){
        return std::cout;
    }else{
        return std::wcout;
    }
}

int main() {
    {
        using CharType = char;
        std::basic_ostream<CharType> & MyTestClass_COUT = get_cout<CharType>();
        MyTestClass_COUT << "Hello";
    }
    {
        using CharType = wchar_t;
        std::basic_ostream<CharType> & MyTestClass_COUT = get_cout<CharType>();
        MyTestClass_COUT << L"World";
    }
}

If you don't have C++17 you can replace if constexpr with a trait-based solution.

Demo.

like image 185
nwp Avatar answered Dec 08 '25 03:12

nwp


Old fashioned trait style solution:

template<class T>
struct cout_trait {};

template<>
struct cout_trait<char> {
    using type = decltype(std::cout);
    static constexpr type& cout = std::cout;
    static constexpr type& cerr = std::cerr;
    static constexpr type& clog = std::clog;
};
template<>
struct cout_trait<wchar_t> {
    using type = decltype(std::wcout);
    static constexpr type& cout = std::wcout;
    static constexpr type& cerr = std::wcerr;
    static constexpr type& clog = std::wclog
};

Usage:

auto& cout = cout_trait<char>::cout;
like image 23
eerorika Avatar answered Dec 08 '25 03:12

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!