c – 针对通用羊羔的编译器推断类型

前端之家收集整理的这篇文章主要介绍了c – 针对通用羊羔的编译器推断类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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(),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; }
};

但是我不明白的是,在代码的这一部分中,加法器在同一时间似乎有两种类型:_lambda< int>和_lambda< string&gt ;.这怎么可能?

解决方法

根据标准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; }
};
原文链接:https://www.f2er.com/c/114372.html

猜你在找的C&C++相关文章