I have a function (used to write logs), which is called in different classes. I do not want to rewrite the code in it for each new class each time (they will be added and removed over time, or, in general, the function will be used later in other projects).

I would like to know the name of the class from which it is called (to set the name of the file and other buns) without passing extra parameters to the function.

Can this be realized? Can boost'om.

2 answers 2

The typeid(object) function returns an object of type type_info with information about the type of the object for which it is called (actually, about the class). This object ( type_info ) has a name() method, which returns the name of the class. To use you need to connect <typeinfo> .

So in the end, to get the class name you need to use

typeid(*this).name()

Or, if the function is not a class method, pass the object itself or the dereferenced pointer to typeid .

  • No one guarantees that name() will return the "human" name. As practice shows, in some compilers, these names can not say anything to a person. - ixSci

Own means of c ++ do not allow to know anything about the context of a function call.

The call stack can be analyzed using some external operating system libraries / APIs. For example: http://man7.org/linux/man-pages/man3/backtrace.3.html https://msdn.microsoft.com/en-us/library/ms680650%28VS.85%29.aspx . But for the use of these tools may impose additional restrictions on the collected code (assembly with debug information, etc.).

It is more reasonable, IMHO, to transfer the context of the call explicitly: this will allow you to use the "regular" means of c ++: __FILE__ , __LINE__ , __func__ , .... You can disguise the context extraction with the macro:

  struct Context{ const char* file; unsigned line; const char* function; }; // Work around MSVS #ifndef __func__ #define __func__ __FUNCTION__ #endif #define CONTEXT() Context({ __FILE__, __LINE__, __func__}) void foo( int a, int b, Context c ); #define FOO(a, b) foo( a, b, CONTEXT() ) 

The class name can be extracted either by __FUNCTION__ name __FUNCTION__ , or from the this pointer:

  typeid(this).name() 

But I don’t want to include this call to this in a macro, since functions can be called from a context, a static function.

On the other hand, for the purposes of log separation, __FILE__ may be enough.

  • Only you need the name of the class, not the function ... - Dmitry
  • non-standard __PRETTY_FUNCTION__ contains the name of the class. It works, like, on all known compilers. Those. you need to wrap the call into a macro, where the __PRETTY_FUNCTION__ argument will be __PRETTY_FUNCTION__ , and inside you can already parse and remove the necessary one. Well, or run on a stack, which is also non-standardized. - Monah Tuk
  • More precisely, MSVC class name even displays for __FUNCTION__ , so you can play with #ifdef/#else/#endif - Monah Tuk