如何在预处理阶段获取c ++函数调用者名称

Moh*_*hit 3 c++ template-meta-programming c-preprocessor preprocessor-meta-program c++11

我必须使用PERF_INSTRUMENT库中的宏.PERF_INSTRUMENT期望用户提供c样式字符串作为函数名称来打印此仪器点的位置.

但是,我不想每次使用时编写函数名称,PERF_INSTRUMENT而是想要调用它,__func__ 以便函数名称自动包含在perf日志中.

但是当我使用__func__它时实际返回operator()是因为__func__它嵌入在lambda函数中.

他们可以通过哪种方式将main()函数名称传递给PERF_INSTRUMENT宏.

#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());
}
Run Code Online (Sandbox Code Playgroud)

请注意,我只能更改MY CODE行下面的代码

max*_*x66 5

他们可以通过哪种方式将主函数名称传递给PERF_INSTRUMENT宏.

您可以将" name"作为参数传递给lambda本身.

有点像

#define PERF_INSTRUMENT(name) \
    auto instObj = [](char const * str) \ // <-- receive an argument
       { static_assert( Is_C_String_Literal< decltype( name ) >::value, \
                       "input argument must be a c-string literal" );\
         /* Some other Logic*/ \
         printf(str); \  // <-- print the argument received, not directly name
         return 1;\
       }(name)
//.......^^^^   pass name as argument
Run Code Online (Sandbox Code Playgroud)

Bonus Off主题建议:检测是一个对象是一个C字符串文字,我提出了另一种方法

template <typename T>
constexpr std::false_type islHelper (T, long);

template <typename T, std::size_t N>
constexpr std::true_type islHelper (T const(&)[N], int);

template <typename T>
using isStringLiteral = decltype(islHelper(std::declval<T>(), 0));
Run Code Online (Sandbox Code Playgroud)

static_assert()成为

static_assert( isStringLiteral<decltype(name)>::value,
               "input argument must be a c-string literal" );
Run Code Online (Sandbox Code Playgroud)