如何根据定义的字符串类型在`std :: cout`和`std :: wcout`之间进行选择?

hkB*_*sai 1 c++ string compile-time c++17

我在代码中定义了自己的字符串类型.

typedef wchar_t CharType;
typedef std::basic_string<CharType> StringType;
Run Code Online (Sandbox Code Playgroud)

我有一个静态类(它没有实例),它将在屏幕上打印字符串消息.我决定放一个COUT静态成员,它将引用std::coutstd::wcout根据我定义的字符串类型.

标题:

#include <ostream>

class MyTestClass
{
    public:
        // ...
        static std::basic_ostream<CharType> & COUT;
        // ...
}
Run Code Online (Sandbox Code Playgroud)

CPP:

std::basic_ostream<CharType> & MyTestClass::COUT = /* How do I initialize this? */;
Run Code Online (Sandbox Code Playgroud)

有没有办法初始化这个静态成员COUT

nwp*_*nwp 5

这是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";
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您没有C++ 17,则可以if constexpr使用基于特征的解决方案进行替换.

演示.


eer*_*ika 5

老式特质风格解决方案:

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
};
Run Code Online (Sandbox Code Playgroud)

用法:

auto& cout = cout_trait<char>::cout;
Run Code Online (Sandbox Code Playgroud)