簡體   English   中英

如何根據定義的字符串類型在`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;

我有一個靜態類(它沒有實例),它將在屏幕上打印字符串消息。 我決定根據我定義的字符串類型放置一個COUT靜態成員,該成員將引用std::coutstd::wcout

標頭:

#include <ostream>

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

CPP:

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替換為基於特征的解決方案。

演示

老式特征樣式解決方案:

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;

您還可以使用專門的類為您進行選擇:

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開始工作,盡管在此之前可以稍作修改以使其工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM