C++20 将熟悉的模板 lambda 作为类模板传递给类的模板参数
考虑将可调用的类模板作为模板参数传递给某个类。以下三种方法,但只有函子一种有效。
朴素的模板函数失败了,因为它不能作为类模板;但是,为什么 C++20 熟悉的模板 lambda 失败了? https://godbolt.org/z/MaYdqx1do
template <typename T>
T SomeFunc() {
return T{};
}
template <typename T>
struct SomeFunctor {
T operator()() const { return T{}; }
};
auto SomeLambda = []<typename T>() { return T{}; };
template <template <typename> class F>
struct Foo {
int operator()() const { return F<int>()(); }
};
int some_func_result = Foo<decltype(&SomeFunc)>()(); // cannot compile
int some_functor_result = Foo<SomeFunctor>()();
int some_lambda_result = Foo<decltype(SomeLambda)>()(); // cannot compile
Consider passing a callable class template as a template parameter to some class. Three approaches as below but only functor one works.
The naive template function failed because it cannot serve as a class template; However, why the C++20 familiar template lambda fails? https://godbolt.org/z/MaYdqx1do
template <typename T>
T SomeFunc() {
return T{};
}
template <typename T>
struct SomeFunctor {
T operator()() const { return T{}; }
};
auto SomeLambda = []<typename T>() { return T{}; };
template <template <typename> class F>
struct Foo {
int operator()() const { return F<int>()(); }
};
int some_func_result = Foo<decltype(&SomeFunc)>()(); // cannot compile
int some_functor_result = Foo<SomeFunctor>()();
int some_lambda_result = Foo<decltype(SomeLambda)>()(); // cannot compile
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让我回答我自己的问题。熟悉的模板 lambda(在 C++ 20 中引入)就像匿名函子(函数对象),但在运算符而不是类上进行模板化。理论上它本质上可以转化为下面的函子类。因此,用户类无法将其应用为其模板参数的类模板。 https://godbolt.org/z/1TddKan6n
Let me answer my own question. Familiar template lambdas(introduced in c++ 20) are like anonymous functors(function object) but templated on the operator instead of on the class. It essentially translates to below functor class in theory. Therefore there's no way for the user class to apply it as a class template for its template argument. https://godbolt.org/z/1TddKan6n