C++如何在宏调用后平衡括号?

C++ how can I balance the brackets after the macro call?

本文关键字:平衡 调用 C++      更新时间:2023-10-16
#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必须返回除空之外的其他东西。

警告我不确定是否允许编译器删除未使用的捕获值。