变量+值宏扩展

时间:2009-10-16 15:14:42

标签: c++ c

我试过没有任何结果。 我的代码如下所示:

#include "stdafx.h"
#include <iostream>

#define R() ( rand() )
#define H(a,b) ( a ## b )
#define S(a) ( # a )
#define CAT() H(S(distinct_name_), R())


int main(int argc, _TCHAR* argv[])
{
    std::cout << CAT() << std::endl; 
    std::cout << CAT() << std::endl;
    std::cout << CAT() << std::endl;
    return 0;
}

我想得到这样的结果:

distinct_name_12233
distinct_name_147
distinct_name_435

as a result of concatenating 
distinct_name_ (##) rand() 

现在我收到一个错误: 术语不评估为采用1个参数的函数。 这是可以实现的吗?

编辑: 几个小时后我终于成功了。预处理器仍然做我完全无法理解的奇怪事情。在这里:

#include "stdafx.h"
#include <iostream>

class profiler 
{
public:
    void show()     
    {
        std::cout << "distinct_instance" << std::endl;      
    }
};

#define XX __LINE__
#define H(a,b) ( a ## b )
#define CAT(r) H(distinct_name_, r)
#define GET_DISTINCT() CAT(XX)
#define PROFILE() \
    profiler GET_DISTINCT() ;\
    GET_DISTINCT().show() ; \


int main(int argc, _TCHAR* argv[])
{

    PROFILE()
    PROFILE()
    return 0;
}

输出是:

distinct_instance
distinct_instance

感谢@Kinopiko提出__LINE__提示。 :)

4 个答案:

答案 0 :(得分:6)

不,你不能这样做。宏是一个编译时的东西,只在运行时调用函数,所以你无法从rand()获得一个随机数到宏扩展中。

答案 1 :(得分:3)

我看到很多人已经正确回答了这个问题,但作为另一种建议,如果您的预处理器实现__TIME____LINE__,您可以获得与您想要的结果非常相似的结果行号或时间连接,而不是随机数。

答案 2 :(得分:0)

你实际得到的是......

std::cout << distinct_name_rand() << std::endl; 

distinct_name_rand()不是函数,因此编译错误失败。

宏在编译期间不执行函数。

答案 3 :(得分:0)

由于在编译时计算宏,因此必须将运行时计算值传递给宏。 尝试:

#define H(a,b) ( a ## b )
#define S(a) ( # a )
#define CAT(r) H(S(distinct_name_), r)

std::cout << CAT(rand()) << std::endl;