C++20 将熟悉的模板 lambda 作为类模板传递给类的模板参数

发布于 2025-01-10 06:44:46 字数 828 浏览 2 评论 0原文

考虑将可调用的类模板作为模板参数传递给某个类。以下三种方法,但只有函子一种有效。

朴素的模板函数失败了,因为它不能作为类模板;但是,为什么 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风月客 2025-01-17 06:44:46

让我回答我自己的问题。熟悉的模板 lambda(在 C++ 20 中引入)就像匿名函子(函数对象),但在运算符而不是类上进行模板化。理论上它本质上可以转化为下面的函子类。因此,用户类无法将其应用为其模板参数的类模板。 https://godbolt.org/z/1TddKan6n

auto SomeLambda = []<typename T>() { return T{}; };

struct SomeLambdaGut {
    template <typename T>
    T operator()() const { return T{}; }
};

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

auto SomeLambda = []<typename T>() { return T{}; };

struct SomeLambdaGut {
    template <typename T>
    T operator()() const { return T{}; }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文