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>()>’ requestedAny 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(); };更多推荐
发布评论