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