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

问题描述 投票:0回答:1
#define function(...) [](){ DO_STUFF(__VA_ARGS__)

因为宏中的开括号,我留下了一个丑陋的用法,不是少了一个括号就是多了一个括号。有什么办法可以解决这个问题吗?

function(a, b, c)
    foo();
}
function(a, b, c){
    foo();
}}
c++ c c-preprocessor variadic
1个回答
1
投票

你可以利用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;
}

输出中引入的lambda捕获初始化器。

12345balanced

这里有一个 现场演示. 要做到这一点 do_stuff 必须返回无效值以外的东西。

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

© www.soinside.com 2019 - 2024. All rights reserved.