c++ - 参数包上的广义 lambda 捕获?

标签 c++ lambda c++14 variadic-functions

在 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/

相关文章:

java - 如何使用 Lambda 表达式对 KeyValue 对象执行 Key 过滤?

c++ - 是否保证 `std::list::splice(std::const_iterator pos, std::list&& other)`保留 `other`为空?

c++ - 段。由指向结构指针的 vector 的指针引起的退出错误

c++ - 指针在使用前必须先初始化,那么char *p怎么理解?

c++ - 在 C++ 中为基于文本的杆位游戏移动汽车时遇到问题

c++ - 基于 list 的 ETW 提供程序 - 解码文件位置

c++ - 按非惰性 lambda 表达式/投影排序

c# - 如何根据顺序排序

lambda - Java 8 流 api 如何将列表收集到对象

c++ - gcc vs clang - 使用 `make_overload` 可变 lambda 继承时的模糊重载