通用Lambda的熟悉模板语法 [英] Familiar template syntax for generic lambdas
问题描述
对于c ++ 20,建议为通用lambda添加以下语法 p0428r2.pdf
For c++20 it is proposed to add the following syntax for generic lambdas p0428r2.pdf
auto f = []<typename T>( T t ) {};
但是gcc 8中的当前实现不接受以下实例化:
But the current implementation in gcc 8 did not accept the following instantiation:
f<std::string>("");
这是gcc的实现错误还是缺少语言功能?我知道我们谈论的是提案,而不是经过批准的规范。
Is that a implementation bug in gcc or a missing language feature? I know we talk about a proposal and not a approved specification.
完整示例(与模板函数语法相比):
Complete example ( with comparison to template function syntax ):
template <typename T> void n( T t ) { std::cout << t << std::endl; }
auto f = []<typename T>( T t ) { std::cout << t << std::endl; };
int main()
{
f<std::string>("Hello"); // error!
n<std::string>("World");
}
抱怨以下错误:
main.cpp:25:22:错误:'>'令牌
f( Hello)之前的预期主表达式;
main.cpp:25:22: error: expected primary-expression before '>' token f("Hello");
推荐答案
lambda表达式的结果不是函数;它是一个 object 函数。也就是说,它是一个具有 operator()
重载的类类型。因此:
The result of a lambda expression is not a function; it is a function object. That is, it is a class type that has an operator()
overload on it. So this:
auto f = []<typename T>( T t ) {};
等效于此:
struct unnamed
{
template<typename T>
void operator()(T t) {}
};
auto f = unnamed{};
如果要为lambda函数显式提供模板参数,则必须调用 operator()
显式地: f.operator()<模板参数>(参数);
。
If you want to explicitly provide template arguments to a lambda function, you have to call operator()
explicitly: f.operator()<template arguments>(parameters);
.
这篇关于通用Lambda的熟悉模板语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!