User defined conversion operator as argument for printf

Posted by BC on Stack Overflow See other posts from Stack Overflow or by BC
Published on 2010-03-21T10:31:40Z Indexed on 2010/03/21 10:41 UTC
Read the original article Hit count: 309

Filed under:
|
|
|
|

I have a class that defined a user defined operator for a TCHAR*, like so

CMyClass::operator const TCHAR*() const
{
    // returns text as const TCHAR*
}

I want to be able to do something like

CMyClass myClass;
_tprintf(_T("%s"), myClass);

or even

_tprintf(_T("%s"), CMyClass(value));

But when trying, printf always prints (null) instead of the value. I have also tried a normal char* operator, as well variations with const etc. It only works correctly if I explicitly call the operator or do a cast, like

_tprintf(_T("%s\n"), (const TCHAR*)myClass);
_tprintf(_T("%s\n"), myClass.operator const TCHAR *());

However, I don't want to cast. How can this be achieved?

Note, that a possibility is to create a function that has a parameter of const TCHAR*, so that it forcible calls the operator TCHAR*, but this I also don't want to implement.

© Stack Overflow or respective owner

Related posts about c++

Related posts about user-defined