C++ 不需要的类型推导

标签 c++ templates c++11 c++14

我有以下两个功能:

  template<class F, class... Args>
  auto runAt(F&& function, const std::chrono::steady_clock::time_point& timePoint, Args&&... args)
    -> std::future<typename std::result_of<F(Args...)>::type> {
    using return_type = typename std::result_of<F(Args...)>::type;
    std::future<return_type> futureResult;

    auto packagedTask = std::make_shared<std::packaged_task<return_type()> >
    (std::bind(std::forward<F>(function), std::forward<Args>(args)...));
    futureResult = packagedTask->get_future();

    this->addTask(Task([this, packagedTask]() {
        (*packagedTask)();
      }), timePoint);
    return futureResult;
  }

  void runAt(const Task& task,
             const std::chrono::steady_clock::time_point& timePoint);

在我的 main.cpp 文件中,我创建了一个 Task 对象,为其分配了一个函数并将其推送到我的调度程序中。 runAt 是调度程序的函数。

这是代码:

... // Task initialization
scheduler.runAt(task, std::chrono::steady_clock::now());

问题是调用了模板化函数,而不是调用以 Task 作为参数的函数。我知道这两个函数都是有效的,因为第一个参数是模板化的并且可变参数对象是空的。

我有两个问题:

1)如何调用第二个方法(考虑返回类型不一样)

2) 不是很重要,但我很好奇这在编译过程中如何不会失败

  auto packagedTask = std::make_shared<std::packaged_task<return_type()> >
    (std::bind(std::forward<F>(function), std::forward<Args>(args)...));

最佳答案

1) How to call the second method (consider that the return types are not the same)

约束第一个。

template<class F, class... Args,
         class = std::enable_if_t<!std::is_same<std::decay_t<F>, Task>{}>>
auto runAt(F&& function, const std::chrono::steady_clock::time_point& timePoint, 
           Args&&... args)
  -> std::future<typename std::result_of<F(Args...)>::type> {
  /* ... */
}

顺便说一下,

auto packagedTask = std::make_shared<std::packaged_task<return_type()> >
(std::bind(std::forward<F>(function), std::forward<Args>(args)...));

不正确。 bind对你不想要的嵌套绑定(bind)和占位符进行特殊处理,因为你将返回类型计算为 typename std::result_of<F(Args...)>::type .

关于C++ 不需要的类型推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32337431/

相关文章:

c++ - 是否有像 auto_ptr 和 shared_ptr 这样不需要 C++0x 的通用智能指针?

c++ - STL 容器 list、deque、vector 等的基类是什么?

c++ - 如何在静态方法中实例化当前类的实例?

c++ - 为什么别名模板给出冲突的声明?

c++ - C++0x 的哪些功能肯定会保留(如果有的话)?

c++ - 在 C++ 中键入安全数字常量

c++ - 可中断线程类 C++11 - 出现错误?

c++ - 可变参数模板提取

c++ - 模拟 GCC 的 __builtin_unreachable?

templates - 如何使用 Go 模板在单个语句中使用多个参数