簡體   English   中英

如何為 std::cout 初始化自定義模擬?

[英]How to initialize custom analogue for std::cout?

我正在嘗試實現自己的basic_string ,但在打印字符串時遇到了問題。 我不會使用std::char_traits和 std 的其他特征,因為我自己已經實現了。 如何創建可用於我的字符串的std::cout的直接模擬並為此使用std::basic_ostream (不會自己創建basic_ostream )。

我嘗試了一些解決問題的方法。 我創建了以下運算符:

template<typename CharType, typename CharTraits>
std::basic_ostream<CharType, CharTraits>& 
operator<<(std::basic_ostream<CharType, CharTraits>& o, const AnyString<CharType, CharTraits>& str)
{
    using size_type = AnyString<CharType, CharTraits>::size_type;
    for (size_type i = 0u; i < str.size(); ++i)
    {
        o << str[i];
    }

    return o;
}

然后我嘗試像這樣將它與std::cout一起使用:

cout << str;

但問題是:“沒有運算符<<匹配這些操作數”。 原因是 std::cout 使用std::char_traits<char>而不是我開發的CharTraits<char, int>

我決定創建自己的std::cout版本:

using Ostream = std::basic_ostream<char, CharTraits<char, int> >;
Ostream Cout;

但它不會因為這個原因編譯:

std::basic_ostream<char,CharTraits<char,int>>':沒有合適的默認構造函數可用

我需要了解初始化我的std::cout版本的最合適方法是什么。

如何創建可用於我的字符串的std::cout的直接模擬並為此使用std::basic_ostream

您根本不需要創建自定義ostream 您只需要為標准std::ostream重載operator<< ,例如:

template<typename CharType, typename CharTraits>
std::ostream& operator<<(std::ostream& o, const AnyString<CharType, CharTraits>& str)
{
    // print the contents of str to out as needed...
    using size_type = AnyString<CharType, CharTraits>::size_type;
    for (size_type i = 0u; i < str.size(); ++i)
    {
        o << (char) str[i];
    }

    return o;
}

或者,如果您希望ostream匹配您的字符串的CharType (即,對char字符串使用std::cout ,對wchar_t字符串使用std::wcout等),您可以改用它:

template<typename CharType, typename CharTraits>
std::basic_ostream<CharType>& operator<<(std::basic_ostream<CharType>& o, const AnyString<CharType, CharTraits>& str)
{
    // print the contents of str to out as needed...
    using size_type = AnyString<CharType, CharTraits>::size_type;
    for (size_type i = 0u; i < str.size(); ++i)
    {
        o << str[i];
    }

    return o;
}

例如,以下代碼: ... 由於這個原因無法編譯:

那是因為您正在嘗試創建std::basic_ostream的默認構造實例,它沒有默認構造函數。 這與您的自定義字符串 class 無關。

暫無
暫無

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

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