C++使用__COUNTER__自动生成不同的命名函数

Vij*_*jay 0 c++ macros googletest c-preprocessor

我想生成不同的命名函数,用于编写单元测试用例.我想这样做基本上为每个单元测试用例赋予唯一的名称.

我正在使用谷歌测试框架来编写单元测试用例.我必须用来TEST_Macro编写单元测试用例.我想自动为每个单元测试提供递增的数字.

这是我的(非工作)代码:

#include <iostream>
using namespace std;

#define join(x, y) x## y

void join(test, __COUNTER__)()
{
    cout << "\n 1";
}

void join(test, __COUNTER__)()
{
    cout << "\n 2";
}

int main()
{
    cout << "Hello world!" << endl;

     test0() ;
     test1() ;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

使用生成唯一函数名的正确方法是什么__COUNTER__

Mat*_*son 6

所以这是旧的"在评估宏参数之前发生粘贴",所以你得到test__COUNTER__而不是test0.

你需要做一个嵌套的宏:

#define expandedjoin(x,y) x##y
#define join(x, y) expandedjoin(x, y)
Run Code Online (Sandbox Code Playgroud)

(你的代码的其余部分会产生很多错误,因为你传递了一个void函数cout,这是不好的)

完整的工作代码:

#include <iostream>
using namespace std;
#define expandedjoin(x,y) x##y
#define join(x, y) expandedjoin(x, y)

void join(test, __COUNTER__)()
{
    cout << "\n 1";
}

void join(test, __COUNTER__)()
{
    cout << "\n 2";
}

int main()
{
    cout << "Hello world!" << endl;

    test0();
    test1();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)