c++11模板类返回类型

问题描述

一个简单的类

   struct Test{
        void display(int x)
        {
           printf("%d\n",x);
        }
    };

c++11

template<class F,class... Args>
auto enqueue(F&& f,Args&&... args) -> std::future<decltype(f(args...))>{

    auto task = std::make_shared<std::packaged_task<decltype(f(args...)())>>(
        std::bind(std::forward<F>(f),std::forward<Args>(args)...)
    );
    return task->get_future();
}

调用它只是使用(cls是上面模板函数的类的对象)

Test test;
cls->enqueue(&Test::display,&test,0);

编译器错误

candidate template ignored: substitution failure 
[with F = void (TestMem::*)(int),Rest = <TestMem *,int>]: called object type 'void (TestMem::*)(int)' is not a function or function pointer
        auto enqueue(F && f,Rest&&... rest) ->std::future<decltype(f(rest...))> {

以上在非类成员函数上运行良好,有人可以在 c++11 上提供修复

c++14 工作正常,但我的项目需要 c++11

template<class F,Args&&... args) {

    using return_type = typename std::result_of<F(Args...)>::type;

    auto task = std::make_shared<std::packaged_task<return_type()>>(
        std::bind(std::forward<F>(f),std::forward<Args>(args)...)
    );
    return task->get_future();
}

解决方法

将返回类型定义为 std::future::type> 解决问题