質問

I have some behaviour that I do not understand. I observed this on VS2005, but IDEONE (using GCC 4.7.2) outputs basically the same.

Here's the code:

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

Here's the output:

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

What's going on here?!?

役に立ちましたか?

解決

There is a partial specialization for basic_ostream

template<class _TraitsT>
basic_ostream<char, _TraitsT>&
   operator<<(basic_ostream<char, _TraitsT>& _Stream, const char* _String);

which is a good fit for the cout << UserString() case.

There is nothing similar for wchar_t and WUserString(), so the member function

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

will be the best match for that (as in most "unusual" cases).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top