0

My test class XString has two cast operators. But the compiler do not use the explicit cast operator const wchar_t*() for fooA. Why?

class XString
{
public:
    operator const CString&();
    explicit operator const wchar_t*();
};

void fooA(const wchar_t* s);
void fooB(const CString& s);

void test()
{
    XString x;

    CString c = x; //OK

    fooA(x); //Error C2664: 'void fooA(const wchar_t *)': cannot convert argument 1 from 'XString' to 'const wchar_t *'

    fooB(x); //OK
}
Holt
  • 36,600
  • 7
  • 92
  • 139

1 Answers1

3

Since operator const wchar_t* is explicit, the conversion will not be done implicitly. That is the point of explicit.

You can force the conversion using static_cast:

fooA(static_cast<const wchar_t*>(x));
asu
  • 1,875
  • 17
  • 27