我正在尝试改造两段遗留代码。其中一个部分实现了函数调用的超时。到目前为止,它已用于 C++ 方法并完美运行。
现在,需要实现与旧 C 库类似的超时。我正在尝试为此使用相同的代码,但遇到了问题。
这是代码的简化版本,其中包含我面临的问题。
uint32_t myFunc1()
{
return 0;
}
uint32_t myFunc2(uint32_t a)
{
return a;
}
int main()
{
uint32_t dummy = 1;
timedCall(myFunc1); //compiles fine.
timedCall(myFunc2, dummy); //compile errors C2672, C2893
}
template <class F, class... Args>
uint32_t timedCall(F &&f, Args&&... a)
{
try
{
std::packaged_task<uint32_t(Args...)> myTask(std::bind(f, a...));
auto res = myTask.get_future();
std::thread(std::move(myTask), a...).detach(); //This is where the issue is.
//Do other stuff
}
catch(...)
{
//handle exceptions
}
return 0; //return something
}
我收到以下错误:
C2672 'std::invoke': no matching overloaded function found
C2893 Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'
有人可以告诉我我做错了什么以及如何解决吗?我正在使用 Visual Studio 2015。
最佳答案
问题是 std::thread 不接受 packaged_task,std::thread(f, a...)
工作正常。现在我不会尝试在 std::thread
水域中运输(编辑:,其中 Andrei R. 提供了很好的详细解释,详细说明了问题所在),而 std::async
将使您的任务更容易:
template <class F, class... Args>
uint32_t timedCall(F &&f, Args&&... a)
{
try
{
auto res = std::async
(
std::launch::async,
std::forward<F>(f),
std::forward<Args>(a)...
);
//Do other stuff
}
catch(...)
{
//handle exceptions
}
return 0; //return something
}
关于c++ - 将 C 函数和参数作为右值引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38341837/