c++ - 将 C 函数和参数作为右值引用传递

标签 c++ windows visual-studio templates c++11

我正在尝试改造两段遗留代码。其中一个部分实现了函数调用的超时。到目前为止,它已用于 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/

相关文章:

visual-studio - MSB3644 找不到框架的引用程序集

c++ - 结构中的运算符重载

c++ - OpenMP 4.5 任务依赖和执行顺序

c++ - 32kB的编译代码是多少

c# - 如何确定类型是否实现 Powershell 中的接口(interface)

c++ - 如何使用 CMake 查找使用 VS 2017 编译的 Boost 文件系统库?

c++ - 内存分配使操作系统崩溃。除了操作系统,谁应该受到指责

mysql从linux转储到windows

java - 如何覆盖 windows32 中的 java.exe

windows - 提取文件的一部分并存储在批处理文件中的变量中