为什么隐式转换不适用于宽ostream?

时间:2013-07-05 10:02:26

标签: c++ operator-overloading iostream overload-resolution

我有一些我不明白的行为。我在VS2005上观察到了这一点,但IDEONE (using GCC 4.7.2) outputs基本相同。

以下是代码:

#include <iostream>
#include <string>

struct UserString {
    const char* p;
        operator const char*() const {
                std::cout << "! " << __FUNCTION__ << std::endl;
                return p;
        }

        UserString()
        : p ("UserString")
        { }
};

struct WUserString {
        const wchar_t* p;
        operator const wchar_t*() const {
                std::cout << "! " << __FUNCTION__ << std::endl;
                return p;
        }

        WUserString()
        : p (L"WUserString")
        { }
};


int main() {
        using namespace std;
        cout << "String Literal" << endl;
        cout << string("std::string") << endl;
        cout << UserString() << endl;
        cout << static_cast<const char*>(UserString()) << endl;

        wcout << L"WString Literal" << endl;
        wcout << wstring(L"std::wstring") << endl;
        wcout << WUserString() << endl;
        wcout << static_cast<const wchar_t*>(WUserString()) << endl;

        return 0;
}

这是输出:

String Literal
std::string
! operator const char*  **** "works"
UserString              ****
! operator const char*
UserString
WString Literal
std::wstring
! operator const wchar_t*  **** "doesn't" - op<<(void*) is used
0x80491b0                  ****
! operator const wchar_t*
WUserString

这里发生了什么?!?

1 个答案:

答案 0 :(得分:3)

basic_ostream

有部分专业化
template<class _TraitsT>
basic_ostream<char, _TraitsT>&
   operator<<(basic_ostream<char, _TraitsT>& _Stream, const char* _String);

非常适合cout << UserString()案例。

wchar_tWUserString()没有类似内容,因此成员函数

basic_ostream& operator<<(const void* _Address);

将是最佳匹配(如在大多数“不寻常”情况下)。