Custom conversion operator as argument to printf

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

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 you try printf always prints (null) instead of a value. I also tried the usual char * operator, as well as options with constant, etc. It only works correctly if I explicitly call the operator or perform an acting mood, for example

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

However, I do not want to quit. How can this be achieved?

Please note that it is possible to create a function that has the const parameter TCHAR *, so that it forcibly calls the TCHAR * operator, but I also do not want to implement this.

+3
4

. , , . operator const TCHAR*() const TCHAR *str() const.

+2

++ , , , - , ? , , printf.

+9

, . , . , printf() ... . , , .

, printf("%s", foo), foo, , printf(), %s, . ( ).

. , , CMyClass, TCHAR *. , , , . (, CMyClass cmc; cmc + 10 , TCHAR * + int .) explicit.

+1

Casting is the right thing if you want to use printf type APIs and rely on the conversion operator (and I will not argue here whether to use these functions). However, I would use static translation, for example._tprintf(_T("%s\n"), static_cast<const TCHAR*>(myClass));

0
source

Source: https://habr.com/ru/post/1737895/


All Articles