c++ - 通用 lambda 的编译器推导类型

标签 c++ lambda c++14 type-deduction

this article , 给出如下代码:

std::vector<int> ivec = { 1, 2, 3, 4};
std::vector<std::string> svec = { "red", "green", "blue" };
auto adder = [](auto op1, auto op2){ return op1 + op2; };
std::cout << "int result : "
          << std::accumulate(ivec.begin(),
                             ivec.end(),
                             0,
                             adder)
          << "\n";
std::cout << "string result : "
          << std::accumulate(svec.begin(),
                             svec.end(),
                             std::string(""),
                             adder)
          << "\n";

如果我没理解错的话,编译器会生成一个很像这个的内部类:

template<class T>
class _lambda
{
  public:
  T operator()(T lhs, T rhs) { return lhs + rhs; }
};

但是我不明白的是,在这段代码中,adder好像同时有两个类型:_lambda<int>_lambda<string> .这怎么可能?

最佳答案

根据标准 5.1.2/p5 Lambda 表达式[expr.prim.lambda]:

For a generic lambda, the closure type has a public inline function call operator member template (14.5.2) whose template-parameter-list consists of one invented type template-parameter for each occurrence of auto in the lambda’s parameter-declaration-clause, in order of appearance.

因此,实际生成的是:

class _lambda {
public:
    template<typename T1, typename T2>
    auto operator()(T1 lhs, T2 rhs) const { return lhs + rhs; }
};

关于c++ - 通用 lambda 的编译器推导类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34545551/

相关文章:

c++ - 为什么我们在C++标准中没有 'const iterator',而是const_iterator?

c++ - 为什么 gcc 生成一个 memmove 而不是 memcpy 来复制 std::vector<>?

c++ - 如何创建抽象类的内联实现?

c++11 lambda高阶函数包装器递归错误

c++ - 怎么知道哪段内存全为零

c# - 运行时 C# 中 Lambda 表达式中的多个条件

c# - lambda表达式和方法组的区别

c++ - 使用 std::unique_ptr/std::shared_ptr const 正确组合

c++ - 哪些编程语言使用它以及它是如何工作的

c++ - 使用基于嵌套值的索引 boost 多索引容器