制作一个指向两个函数c++的std::函数

making a std::funtion that points to two functions c++

本文关键字:函数 两个 c++ std 一个      更新时间:2023-10-16

如果我有两个函数

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在事件处理程序的上下文中。

有几个可能的解决方案:

  1. 第一种是使用lambda或其他函数手动定义多播:

    function<void()> v = []() {
        foo();
        bar();
    };
    v();
    
  2. 第二个是定义自己的完整std::function风格,它支持可变数量的目标。您可以使用template数组(从而避免在运行时使用vector)。。。或者无论如何只使用CCD_ 7。

  3. 第三种选择是简单地包装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();