Functor到可变参数模板功能(Functor to variadic template function)

编程入门 行业动态 更新时间:2024-10-27 21:15:09
Functor到可变参数模板功能(Functor to variadic template function)

我想把仿函数变成functor,但是我得到了编译错误。 这是代码:

template <class T> struct Creator { template <typename...Ts> static std::shared_ptr<T> create(Ts&&... vs) { std::shared_ptr<T> t(new T(std::forward<Ts>(vs)...)); return t; } }; class Car: public Creator<Car> { private: friend class Creator<Car>; Car() { } }; int main() { auto car=Car::create(); std::function< std::shared_ptr<Car> () > createFn=&Car::create; return 0; }

我在第二个语句的GCC 4.6.3中得到以下错误(第一个是OK):

error: conversion from ‘<unresolved overloaded function type>’ to non-scalar type ‘std::function<std::shared_ptr<Car>()>’ requested

任何暗示赞赏。

I want to make functor to generic function, but I get compiler error. Here is the code:

template <class T> struct Creator { template <typename...Ts> static std::shared_ptr<T> create(Ts&&... vs) { std::shared_ptr<T> t(new T(std::forward<Ts>(vs)...)); return t; } }; class Car: public Creator<Car> { private: friend class Creator<Car>; Car() { } }; int main() { auto car=Car::create(); std::function< std::shared_ptr<Car> () > createFn=&Car::create; return 0; }

I get the following error in GCC 4.6.3 on the second statement(the first is OK):

error: conversion from ‘<unresolved overloaded function type>’ to non-scalar type ‘std::function<std::shared_ptr<Car>()>’ requested

Any hint appreciated.

最满意答案

如果需要模板函数的指针,则必须首先实例化模板。

std::function<std::shared_ptr<Car>()> createFn = &Car::create<>;

这将使它在clang ++ 3.1上编译,但g ++ 4.8仍然拒绝编译,我认为这是一个bug。

您可以提供lambda函数:

std::function<std::shared_ptr<Car>()> createFn = []{ return Car::create(); };

If the pointer of a template function is needed, the template must be instantiated first.

std::function<std::shared_ptr<Car>()> createFn = &Car::create<>;

This will make it compile on clang++ 3.1, but g++ 4.8 still refuses to compile, which I believe is a bug.

You could provide a lambda function instead:

std::function<std::shared_ptr<Car>()> createFn = []{ return Car::create(); };

更多推荐

本文发布于:2023-07-07 13:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1063914.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模板   参数   功能   Functor   template

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!