C ++宏问题(解释逗号,) [英] C++ macro problem (interpretation of comma ,)

查看:228
本文介绍了C ++宏问题(解释逗号,)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码编译得很好。

#define CMD_MACRO(pp, cmd)  \
{           \
      if (pp)\
      { cmd; }        \
}

template<class T> void operate_on(T &data, char c) {
  data=data+1;
};

int main() {
  int book=4;
  char c;
    CMD_MACRO(book, {
        operate_on<int>(book, c);
    });
};

请注意,我的代码中的实际宏更复杂,

Note that the actual macro in my code is more complex, I have given a simplified version which may not make much logical sense

现在,如果我在函数中添加另一个模板参数,它会给出编译错误(问题在代码注释中解释):

Now, if I add another template parameter in the function it gives compilation error (problem explained in code comment):

template<class T, bool b> void operate_on(T &data, char c) {
  data=data+1;
};
int main() {
      int book=4;
      char c;
        CMD_MACRO(book, {
            operate_on<int, false>(book, c); /* here the "," between int and 
                  false is being treated 
                  as separating arguments to CMD_MACRO, 
                  instead being part of 'cmd'. Thats strange 
                  because the comma separating book and c is 
                  treated fine as part of 'cmd'. */
        });
};


test.cpp:18:6: error: macro "CMD_MACRO" passed 3 arguments, but takes just 2
test.cpp: In function 'int main()':
test.cpp:16: error: 'CMD_MACRO' was not declared in this scope

如何解决问题(我需要添加额外的模板参数到现有代码,并得到这样的错误)。

How to fix the problem (I need to add that extra template parameter to existing code and am getting such an error).

推荐答案

你尝试过:(operate_on< int,false>(book,c)); ? (注意表达式周围的额外括号)。

Have you tried: (operate_on<int, false>(book, c));? (Notice the extra parentheses around the expression).

我相信预处理器不知道C ++模板,因此将< > 作为任何旧令牌。没有额外的括号,它将 operate_on< int 作为一个参数,并将 false>(book,c)

I believe the preprocessor knows nothing of C++ templates, and so treats the < and > as just any old token. Without the extra parentheses, it treats operate_on<int as one argument, and false>(book, c) as another.

这篇关于C ++宏问题(解释逗号,)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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