C++如何在宏调用后平衡括号?
C++ how can I balance the brackets after the macro call?
#define function(...) [](){ DO_STUFF(__VA_ARGS__)
由于宏中的开括号,我留下了一个丑陋的用法,要么缺少括号,要么有一个额外的括号。有没有办法解决这个问题?
function(a, b, c)
foo();
}
function(a, b, c){
foo();
}}
您可以使用c++14 中引入的 lambda 捕获初始值设定项:
template <class...Args>
int do_stuff(Args&& ... args)
{
((std::cout << args),...); // <-this requires c++17 and is just for illustration.
return 1;
}
#define myfunction(...) [dummy##__LINE__=do_stuff(__VA_ARGS__)]()
int main() {
auto f = myfunction(1,2,3,4,5){std::cout<< "balanced" << std::endl;};
f();
return 0;
}
输出:
12345balanced
这是一个现场演示。要做到这一点do_stuff
必须返回除空之外的其他东西。
警告我不确定是否允许编译器删除未使用的捕获值。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- 变量没有改变?通过向量的函数调用
- 没有为自己的结构调用列表推回方法
- 调用'begin(int [n])'没有匹配函数
- 什么时候调用析构函数
- C++如何在宏调用后平衡括号?
- 使用 .Net 4.0 时出现堆栈不平衡错误,但在使用 .Net 2.0 时不调用堆栈不平衡错误
- C++在递归函数中平衡了树/调用顺序