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

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

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

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

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

Header:

#include <ostream>

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

菲律宾共产党:

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

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

这是 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";
    }
}

如果您没有 C++17,您可以将 if constexpr 替换为基于特征的解决方案。

Demo.

您也可以使用专门的 class 为您进行选择:

template <typename T_Char>
struct StreamSelector;

template <>
struct StreamSelector<char> {
    static constexpr std::ostream &stream = std::cout;
};

template <>
struct StreamSelector<wchar_t> {
    static constexpr std::wostream &stream = std::wcout;
};

std::basic_ostream<CharType> &COUT = StreamSelector<CharType>::stream;

这适用于从 C++11 开始的工作,但可以稍作修改以在此之前工作。

老式特征样式解决方案:

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
};

用法:

auto& cout = cout_trait<char>::cout;