我有以下两个功能:
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/