加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:35:17 所属栏目:百科 来源:网络整理
导读:在 this article,提供以下代码: std::vectorint ivec = { 1,2,3,4};std::vectorstd::string svec = { "red","green","blue" };auto adder = [](auto op1,auto op2){ return op1 + op2; };std::cout "int result : " std::accumulate(ivec.begin(),ivec.end(
在 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; }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读