C++宏问题(逗号的解释)

jee*_*etu 2 c++ syntax macros

以下代码编译正常.

#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);
    });
};
Run Code Online (Sandbox Code Playgroud)

请注意,我的代码中的实际宏更复杂,我给出了一个简化版本,这可能没有太大的逻辑意义

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

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
Run Code Online (Sandbox Code Playgroud)

如何解决问题(我需要将额外的模板参数添加到现有代码中并且遇到这样的错误).

dap*_*wit 6

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

我相信预处理一无所知的C++模板,所以对待<,并>为任何旧的令牌.如果没有额外的括号,它会将其operate_on<int视为一个参数,而false>(book, c)视为另一个参数.