制作一个指向两个函数c++的std::函数
making a std::funtion that points to two functions c++
如果我有两个函数
void foo()
{
std::cout << 1 << std::endl;
}
void bar()
{
std::cout << 2 << std::endl;
}
我有一个函数指针
std::function<void()> v;
我想让v()
打印
1
2
std::function
对目标的定义是const T* target() const
,这意味着它只能存储一个目标。
这个问题以前曾被问过,您所描述的情况在CLR/中被称为"委托多播"。NET在事件处理程序的上下文中。
有几个可能的解决方案:
-
第一种是使用lambda或其他函数手动定义多播:
function<void()> v = []() { foo(); bar(); }; v();
-
第二个是定义自己的完整
std::function
风格,它支持可变数量的目标。您可以使用template
数组(从而避免在运行时使用vector
)。。。或者无论如何只使用CCD_ 7。 -
第三种选择是简单地包装
vector
(警告:伪代码):template<class FuncType> class MulticastFunction { private: vector<std::function<FuncType>> targets; public: void operator()() { for(auto& target : this->targets) { target(); } } void addTarget(FuncType& target) { this->targets->push_back( target ); } }
用法:
MulticastFunction<void()> mc; mc.addTarget( foo ); mc.addTarget( bar ); mc();
相关文章:
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 两个父类的构造函数的序列
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- C++如果两个模板函数都与参数列表匹配,将调用哪个模板
- 如何从两个不同的函数传递参数
- 两个函数模板候选项.将一个参数作为引用后,选择不太专业的模板
- 如何比较两个函数的速度和性能
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- 有一个构造函数,但有两个析构函数
- 为什么系统日志有两个不同的函数声明?
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- C++ 关于两个类构造函数的问题
- 如何创建两个具有相同名称和不同返回类型并基于布尔参数运行的函数
- 如何在构造器的成员初始值设定项列表中调用两个函数?
- 如何将这两个函数组合成一个实现?
- 将函数两个向量合并为第三个向量
- C++朋友函数两个数字的加法