首先是什么-模板实例化与宏扩展? [英] What comes first - template instantiation vs. macro expansion?

查看:53
本文介绍了首先是什么-模板实例化与宏扩展?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑这样的代码示例(将definetemplate组合在一起只是一个人工示例,不要对它有任何意义):

Let's consider a code example like this (it is just an artificial example to combine define and template, don't look for any sense it it):

#define COMMA ,

template <typename A> class Test
{
public:
    Test(){}

    void Foo(A var COMMA int test);
};

Test<int> Knarz;

问题:

是我的假设是正确的那个,第一预处理器将查找/替换逗号所有出现和第二编译器将实例化的顺序任何模板?

Is my assumption correct that, first the preprocessor will search/replace all occurrences of COMMA and second the compiler will instantiate any templates in that order?

<强>跟帖:

如果上面的答案是""(如我希望的那样),您能否解释一下为什么使用模板和定义的解决方案有效吗?

If the above answer is 'yes', as I hope it to be, can you explain why this solution using templates and defines works?

推荐答案

在编译自身完成之前运行预处理程序,因此您认为在模板实例化之前,预处理程序将替换COMMA的假设是正确的.

The preprocessor is run before the compiling itself is done, so your assumption that the preprocessor will replace COMMA before the template is instantiated is correct.

为您的后续行动: 该解决方案有什么与模板.问题在于预处理器会将大括号内的逗号用作宏的参数分隔符,因为它不会解析C ++代码以查看它是模板参数的分隔符.因此,仅在替换MOCK_CONSTANT_METHOD0之后,使用COMMA宏插入,来分隔模板参数.但是我不确定这是否可以保证工作,因为我不知道通过内存对宏替换顺序的保证.如果COMMAMOCK_CONSTANT_METHOD0之前被替换,那么一切都会崩溃,并且代码将再次无法编译.

For your followup: The solution has little to do with templates. The problem there is that the preprocessor will take commas inside the braces to be argument separators for the macro, since it doesn't parse the C++ code to see that it is the separator for the template arguments. So the COMMA macro is used to insert the , for separating template arguments only after the MOCK_CONSTANT_METHOD0 has been substituted. I am however not sure if this is guaranteed to work, since I don't know the guarantees for the order of macro-substitution by memory. If COMMA would be substituted before MOCK_CONSTANT_METHOD0 everything falls apart and the code once again doesn't compile.

在研究了标准之后,我认为该解决方案通常应该可以使用,因为预处理器将首先找到MOCK_CONSTANT_METHOD0并将其替换.只有这样,它才会检查替换结果以找到COMMA宏.虽然没有保证.

After looking into the standard I think the solution should generally work, since the preprocessor will find MOCK_CONSTANT_METHOD0 first and replace it. Only then will it examine the result of the replacement to find the COMMA macro. No guarantees though.

这篇关于首先是什么-模板实例化与宏扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆