可变宏观扩张不按预期工作 [英] variadic macro expension not working as expected
问题描述
void print(bool error, const char* n)
{
cout << (error ? "Error" : "Called ") << n << endl;
}
void print(bool, nullptr_t) {}
template <class ErrorCallback, class Name, class Function, class ...Args>
void tryCall(ErrorCallback c, Name n, Function f, Args&& ...args)
{
try
{
f(forward<Args>(args)...);
print(false, n);
}
catch (const std::exception&)
{
print(true, n);
c();
}
}
#if 1/*some condition*/
#define CALL(c, f, ...) tryCall(c, #f, f, __VA_ARGS__)
#else
#define CALL(c, f, ...) tryCall(c, nullptr, f, __VA_ARGS__)
#endif
void f1(int& a, int b) {}
int main()
{
#define CALL_ON_A(...) CALL([&a](){a=0;}, __VA_ARGS__)
int a = 1;
CALL_ON_A(f1, a, 2);
// expect output: Called f1
// actual output: Called f1, a, 2
return 0;
}
我只想输出函数名称。我应该更改什么才能使其正常工作?
I just want to output the function name. What should I change to make it work?
我正在使用Visual Studio社区2015年更新3。
我还测试了g ++(GCC)5.4.0,-std = c + +11,低于
cygwin NT-10.0 。它按预期工作。
I also tested with g++ (GCC) 5.4.0, -std=c++11, under cygwin NT-10.0. And it works as I expected.
推荐答案
您好tzyu65,
Hi tzyu65,
谢谢在这里发布。
" stringizing" operator(#)将宏参数转换为字符串文字而不扩展参数定义。它仅用于带参数的宏。如果它位于宏定义中的形式参数之前,则宏调用传递的实际参数
将用引号括起来并视为字符串文字。然后,字符串文字替换宏定义中字符串化运算符和形式参数的组合的每次出现。
"stringizing" operator (#) converts macro parameters to string literals without expanding the parameter definition. It is used only with macros that take arguments. If it precedes a formal parameter in the macro definition, the actual argument passed by the macro invocation is enclosed in quotation marks and treated as a string literal. The string literal then replaces each occurrence of a combination of the stringizing operator and formal parameter within the macro definition.
您可以将名称更改为实际参数。试试这样:
You could change the Name as a actual argument. Try like this:
#if 1/*some condition*/
#define CALL(c, n, f,...) tryCall(c, #f, f, __VA_ARGS__)
#else
#define CALL(c, f, ...) tryCall(c, nullptr, f, __VA_ARGS__)
#endif
void f1(int& a, int b) {}
int main()
{
#define CALL_ON_A(n,f,...) CALL([&a](){a=0;},#f, f, __VA_ARGS__)
int a = 1;
CALL_ON_A(f1, f1, a, 2);
// expect output: Called f1
// actual output: Called f1, a, 2
return 0;
}
希望这可以帮到你。
最好的问候,
Sera Yu
这篇关于可变宏观扩张不按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!