微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c++11模板类返回类型

如何解决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> 解决问题

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。