[英]Generic C++14 lambdas and relationship with templates
I did read that C++14 generic lambdas with auto
parameters are actually templates, so the following is valid C++14 我确实读过带有
auto
参数的C ++ 14泛型lambdas实际上是模板,所以以下是有效的C ++ 14
auto glambda = [] (auto a) { return a; };
cout << glambda(23); // Prints 23
cout << glambda('A'); // Prints A
This doesn't quite stack up with what I know from templates.. where's the instantiation point? 这与我从模板中知道的内容并不完全相符..实例化点在哪里? What is it stored in the
glambda
variable if the first call instantiates a template with int
and the second one with char
? 如果第一次调用使用
int
实例化模板而第二次使用char
实例化模板,那么它存储在glambda
变量中的是什么?
It's not that the "lambda is a template" -- that doesn't make sense, a lambda is an expression. 并不是说“lambda是模板” - 这没有意义,lambda是一个表达式。 Rather, the type of the closure object that's defined by the lambda expression has an overloaded function call operator that is defined by a member function template.
相反,由lambda表达式定义的闭包对象的类型具有由成员函数模板定义的重载函数调用运算符。 So the instantiation point is the first use of the respective call operator.
因此,实例化点是相应调用操作符的第一次使用。
In other words, a lambda [a, &b](auto x, auto y) -> R { /* ... */ }
has a type like: 换句话说,lambda
[a, &b](auto x, auto y) -> R { /* ... */ }
的类型如下:
struct __lambda
{
__lambda(const A & __a, B & __b) : a(__a), b(__b) {}
template <typename T1, typename T2>
R operator()(T1 x, T2 y) const { /* ... */ }
private:
A a;
B & b;
};
A generic lambda is an object of a compiler generated type that has a template method called operator()
. 泛型lambda是编译器生成类型的对象,其具有名为
operator()
的模板方法。 Your code can be rewritten with this equivalent: 您可以使用以下等效代码重写代码:
struct MyLambda {
template<typename T>
T operator() (T val) {
return val;
}
};
int main() {
MyLambda func;
std::cout << func('A');
std::cout << func(42);
}
The compiler will instantiate operator()
when needed. 编译器将在需要时实例化
operator()
。
Hope it helped 希望它有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.