如何在C ++ 11的lambda函数参数中不使用具体类型?

C++11 requires that lambda function parameters be declared with concrete types. This is sometimes annoying. auto is really nice, especially when the type is complex like std::vector<std::string>::iterator is quite long to type. I know C++14 allows auto in lambda functions. But how to not use concrete types in lambda function parameters in C++11?

C ++ 11要求使用具体类型声明lambda函数参数。 有时这很烦人。 auto真的很好,特别是当类型很复杂,例如std::vector<std:: string >::iterator ,键入的时间很长。 我知道C ++ 14允许auto输入lambda函数。 但是,如何在C ++ 11的lambda函数参数中不使用具体类型呢?

In C++11, you may let the compiler infer the type for you by using

在C ++ 11中,您可以让编译器通过使用来为您推断类型

decltype(...)

and replace the type declaration with decltype().

并将类型声明替换为decltype()

For example

例如

#include <iostream>
#include <string>
#include <algorithm>

int main ()
{
  std::vector<std::string> ss = {"hello", "world"};

  std::transform(std::begin(ss), std::end(ss), std::begin(ss), [](decltype(*std::begin(ss)) si) {
    return si;
  });

  return 0;
}

decltype(*std::begin(ss)) infers the concrete type automatically for you so that you don’t need to manually write the concrete type delcaration.

decltype(*std::begin(ss))自动为您推断具体类型,因此您无需手动编写具体类型delcaration。

Answered by Eric Z Ma.
埃里克·马(Eric Z Ma)回答。

翻译自: https://www.systutorials.com/how-to-not-use-concrete-types-in-lambda-function-parameters-in-c11/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值