在通用lambda中使用模板参数 [英] Using template parameter in a generic lambda
问题描述
GCC 允许使用以下语法作为扩展名:
GCC allows the following syntax as an extension:
// a functional object that will add two like-type objects
auto add = [] <typename T> (T a, T b) { return a + b; };
在 n3418 ,2012年针对通用lambdas的提案,我们看到允许上述内容的语法:
In n3418, the 2012 proposal for generic lambdas, we see syntax that allows the above:
overload( []<class T>(T* p) {...},
然而,由于它是一个扩展,语法显然不存在(或不允许。)在什么情况下,当我们有auto时,上述是有用的,为什么是syntax (或不允许)?
However, since it is an extension the syntax is clearly absent (or not allowed.) In what situations would the above be useful when we have auto, and why is the syntax absent (or not allowed)?
推荐答案
在我看来,当前的多态lambdas只是更简洁,默认更灵活。
It seems to me that current polymorphic lambdas are just more terse, and more flexible by default.
您可以重现您的示例情况的效果,如下所示:
You can reproduce the effect of your sample situation like the following:
struct A {};
struct B {};
int operator+(A, A) { return 1; }
int operator+(B, B) { return 2; }
int operator+(A, B) { return 3; }
int operator+(B, A) { return 4; }
int main() {
auto add = [](auto a, decltype(a) b) { return a + b; };
auto flexible_add = [](auto a, auto b) { return a + b; };
add(A{}, A{}); // works
add(B{}, B{}); // works
add(A{}, B{}); // doesn't work
flexible_add(A{}, A{}); // works
flexible_add(B{}, B{}); // works
flexible_add(A{}, B{}); // works
auto deref = [](auto *a) { return *a; };
int foo{};
A a;
B b;
deref(&foo); // works
deref(&a); // works
deref(&b); // works
deref(foo); // doesn't work
deref(a); // doesn't work
deref(b); // doesn't work
}
GCC扩展更有能力的一种情况关于可变参数模板参数,如下所示:
The one case where the GCC extension is more capable is regarding variadic template parameters, like the following:
#include <cstddef>
#include <utility>
#include <iostream>
void print(std::initializer_list<std::size_t> il)
{
for (auto&& elem : il) std::cout << elem << std::endl;
}
int main()
{
auto indexed_lambda = [] <std::size_t... Is> (std::index_sequence<Is...>) { print({Is...}); };
indexed_lambda(std::make_index_sequence<5>{});
}
我不讨论涉及包含通用lambda的讨论,但我可以看到一个思考,值得包括当前语法覆盖大多数用例,是简洁的,适合于lambdas的意图,这通常用于生成短代码片段。
I dunno the discussion involving inclusion of generic lambdas, but I can see one pondering whether such extension is worth including when the current syntax covers the majority of use cases, is terse, and appropriate for the intent of lambdas, which most often is for producing short snippets of code.
这篇关于在通用lambda中使用模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!