Override "operator <<" for char and wchar_t combined



  • This is a C++ question I guess. Do you know how to override "operator <<" to handle both char and wchar_t types without the use of wcout for wchar_t?

    I would guess it need to be done with templates but I'm struggling to understand how to use templates here to implement it/ code it.

    Example:

    const char * string1 = "I love Qt"
    const wchar_t * string2 = "I love Qt"

    I can cout << string1 but need to use wcout << string2

    How or can I somehow use/code a generic genout << that combines cout and wcout by using template I guess or what ever it takes?



  • With this operator both char[] and w_char[] will work with cout, assuming you pass null terminated strings:

    @template<typename T>
    ostream& operator<<(ostream& out, T text[])
    {
    while (*text) {
    out << (char)*text;
    ++text;
    }
    return out;
    }@



  • That cast to (char) will only strip away the top bits of a Unicode character. If you look at the basic Unicode table "here":http://www.tamasoft.co.jp/en/general-info/unicode.html, you can imagine that will get you.

    If your compiler supports type information, you can try to detect the type of the character and output accordingly, but that still doesn't fix anything for the first parameter of the << operator if you will be doing the override described above.



  • Or even easier, just switch to wcout - with this operator overload BOTH cout and wcout work with BOTH char and wchar_t, just cast to wchar_t to eliminate cutting off values, promoting char to wchar_t should be trouble-free.

    @template<typename T>
    ostream& operator<<(ostream& out, T* text)
    {
    while (*text) {
    out << (wchar_t)*text;
    ++text;
    }
    return out;
    }

    std::wcout << string1 << endl << string2 << endl;@


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.