【问题标题】:c++11 template class return typec++11模板类返回类型
【发布时间】:2021-05-30 11:38:48
【问题描述】:

一个简单的类

   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, class... Args>
auto enqueue(F&& 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::result_of 在 C++11 中可用。您的最后一个片段应该可以工作,也许是在添加尾随返回类型之后。
  • @IgorTandetnik yeak,你说得对,c++11 必须显式定义返回类型,auto 不行,为成员函数指定返回类型似乎很难

标签: c++ c++11 decltype


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多