3

我必须使用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());
}

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

4

2 回答 2

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

奖金题外话:检测对象是否是 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));

static_assert()成为

static_assert( isStringLiteral<decltype(name)>::value,
               "input argument must be a c-string literal" );
于 2018-11-21T13:11:48.993 回答
0

由于断言存在根本缺陷——它接受任何const字符数组——将宏包装在另一个宏中应该可以工作。
像这样的东西:

#define PERF_FUNCTION do { \
    const char name[] = __func__; \
    PERF_INSTRUMENT(name); \
} while(0)
于 2018-11-21T15:17:13.697 回答