在 C++14 中,我们可以使用广义 lambda 捕获:
template<class T>
auto pack(T t)
{
return [t=std::move(t)](auto&& f){f(t);};
};
但它不能与 param-pack 一起使用:
template<class... T>
auto pack(T... t)
{
return [t=std::move(t)...](auto&& f){f(t...);};
};
是否有任何特殊的语法或进一步的标准提案来解决这个问题?
最佳答案
我的 C++14 草案说 ([expr.prim.lambda]/24):
A simple-capture followed by an ellipsis is a pack expansion (14.5.3). An init-capture followed by an ellipsis is ill-formed.
所以看起来没有办法进行可变参数广义捕获。一种可能的解决方法是仅捕获元组中的参数,然后使用此处建议的解决方案之一:"unpacking" a tuple to call a matching function pointer
auto pack(T... t)
{
return [args=make_tuple(std::move(t)...)](auto&& f){
// find a way to call f with args
};
};
编辑:
它现在被选入 C++20,由 proposal 制作.虽然语法有点不同:
template<class... T>
auto pack(T... t)
{
return [...t=std::move(t)](auto&& f){f(t...);};
};
注意 ...
在 init-capture 之前。
关于c++ - 参数包上的广义 lambda 捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24816557/