c++ - Variadic 模板方法和 std::function - 编译错误

标签 c++ templates c++11 variadic-templates

<分区>

我确定错误非常简单和愚蠢,但我看不到。这是代码:

#include <future>

template <typename ResultType>
class Foo
{
public:
    template <typename ...Args>
    void exec(const std::function<ResultType(Args...)>& task, Args&&... args) {}
};

int main()
{
   Foo<void>().exec([](){});
   return 0;
}

这里是错误:

'void CAsyncTask::exec(const std::function &,Args &&...)' : could not deduce template argument for 'const std::function &' with [ ResultType=void ]

Foo<void>().exec<void>([](){})也不起作用(我更愿意不必手动指定 Args 类型)。

关于建议答案的更新:以下代码确实有效。 CAsyncTask<void>().exec(std::function<void ()>([](){}));

但是这个问题真的没有解决方法吗?我能否以某种方式扩展我的模板以推断出 lambda 参数?

最佳答案

您可以尝试将 exec 的签名更改为

template<typename Fn, typename... Args> 
void exec(Fn&& task, Args&&... args)

然后在函数内部构造你的 std::function

关于c++ - Variadic 模板方法和 std::function - 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30739238/

相关文章:

c++ QueryPerformanceCounter 性能峰值

c++ - 将文件移动到磁盘上的另一个文件夹 - Visual Studio

c++ - 如何重用不同类型的运算符重载?

c++ - 了解 C++ 模板示例

c++ - 函数的属性是什么意思?

c++ - 带有继承析构函数的警告 C4710(未内联)

C++ 在编译时比较模板类型

c++ - 为什么我的 Curiously Recurring Template Pattern (CRTP) 不能引用派生类的 typedef?

c++ - 如何使用基于范围的循环语法遍历 STL 容器中的连续对?

c++ - "two-step"async_read with boost asio