c++ - 如何使用 std::function 作为模板

标签 c++ c++11

我是 std::function 的新手概念。

我需要使用 std::function按照以下方式

我有一个类如下

class A(string ,bool, string, std::function<void()>)

这里是std::function<void()>应该从不同的对象中获取不同的参数。 参数基本上会是不同类型的枚举

例如

1)A a(string ,bool, string, std::function<void(enum xyz)>)
2)A b(string ,bool, string, std::function<void(enum abc)>)
3)A c(string ,bool, string, std::function<void(enum efg)>)

我想知道我应该如何构造 std::function在 A 类中,以便我可以将不同的枚举作为参数传递给 A 类对象

最佳答案

您可以将模板类型作为 std::function 参数传递。这是一个例子:

#include <iostream>
#include <functional>
#include <string>

template <class T>
class Foo
{
public:
   Foo(std::function<void(T)> f) : f_{f} {}

   void call(T in) { f_(in); }

private:
   std::function<void(T)> f_;
};

int main()
{
    Foo<double> fd{[] (double d) { std::cout << d << '\n'; }};
    fd.call(34.2);

    Foo<std::string> fs{[] (std::string s) { std::cout << s << '\n'; }};
    fs.call("Test!");
    return 0;
}

输出:

34.2
Test!

关于c++ - 如何使用 std::function 作为模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40027005/

相关文章:

C++ winsock 在 bind() 上给出 10038 错误

c++ - 我的代码的某些部分没有运行

c++ - 默认模板参数 - 不必来自对吗?为什么有效?

c++ - 不完整类型上的 std::is_constructible

c++ - 十六进制字符到 std::string 的 constexpr 转换

c++ - 构建输出与项目构建顺序不匹配

c++ - 访问 boost::tuple 的成员

c++ - 带有模板函数的 Typedef

c++ - 返回模板的模板

c++ - 警告 C++11 继承的构造函数