mercredi 21 novembre 2018

How to get c++ function caller name at preprocessing stage

I have to use a macro PERF_INSTRUMENT from a library. PERF_INSTRUMENT expects a user provided c-style string as a function name to print the location of this instrument point.

But, I don't want to write the function name everytime I use PERF_INSTRUMENT instead I want to call it with __func__ so that function name is automatically included in the perf log.

But when I use __func__ it actually returns operator() because the __func__ is embedded inside the lambda function.

Is their any way by which I can pass the main() function name to the PERF_INSTRUMENT macro.

#include <cstdio>
#include <cassert> 
#include <type_traits> 

using namespace std;

namespace /* anonymous */
{
    template< typename T >
    struct Is_Const_Char_Array
      : std::is_same< std::remove_reference_t< T >,
                      char const[ std::extent< std::remove_reference_t< T > >::value ] >
    {};

    template< typename T >
    struct Is_C_String_Literal
      : Is_Const_Char_Array< T >
    {};
}

#define PERF_INSTRUMENT(name)  auto instObj = [] { static_assert( Is_C_String_Literal< decltype( name ) >::value, "input argument must be a c-string literal" ); /* Some other Logic*/ printf(name);return 1; }()


// <------------------ MY CODE -------------------> //

int main(){
    PERF_INSTRUMENT("main"); // <-- this works fine
    PERF_INSTRUMENT(__func__); // <-- this prints operator()
    // PERF_INSTRUMENT(__builtin_FUNCTION());
}

Aucun commentaire:

Enregistrer un commentaire