The following code compiles in Visual Studio 2010 but fails to compile in the Visual Studio 2012 RC.
#include <string>
// Windows stuffs
typedef __nullterminated const wchar_t *LPCWSTR;
class CTestObj {
public:
CTestObj() {m_tmp = L"default";};
operator LPCWSTR() { return m_tmp.c_str(); } // returns const wchar_t*
operator std::wstring() const { return m_tmp; } // returns std::wstring
protected:
std::wstring m_tmp;
};
int _tmain(int argc, _TCHAR* argv[])
{
CTestObj x;
std::wstring strval = (std::wstring) x;
return 0;
}
The error returned is:
error C2440: 'type cast' : cannot convert from
'CTestObj'
to'std::wstring'
No constructor could take the source type, or constructor overload resolution was ambiguous
I've already realized that commenting out either of the conversion operators fixes the compile problem. I just want to understand:
If I'm understanding the logic under the hood, the operator overload is trying to copy the code and the object every time you cast. Therefore, you need to return it as a reference instead of attempting to return a new object based on the field. The line:
operator std::wstring() const { return m_tmp; }
should be:
operator std::wstring&() { return m_tmp; }
The following compiles and runs as expected.
#include <string>
// Windows stuffs
typedef __nullterminated const wchar_t *LPCWSTR;
class CTestObj {
public:
CTestObj() {m_tmp = L"default";};
operator LPCWSTR() { return m_tmp.c_str(); } // returns const wchar_t*
operator std::wstring&() { return m_tmp; } // returns std::wstring
protected:
std::wstring m_tmp;
};
int main()
{
CTestObj x;
std::wstring strval = (std::wstring) x;
wprintf(L"%s\n", strval.c_str());
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With