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

标签 c++ std-function

如果我有两个函数

void foo()
{
    std::cout << 1 << std::endl;
}

void bar()
{
    std::cout << 2 << std::endl;
}

我有一个函数指针

std::function<void()> v;

我想要打印v()

1
2

最佳答案

std::function对target的定义是const T* target() const,也就是说它只能存储一个target。

This question has been asked before ,您所描述的情况在事件处理程序的上下文中在 CLR/.NET 中称为“委托(delegate)多播”。

有几种可能的解决方案:

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

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

  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();
    

关于c++ - 制作一个指向两个函数的 std::function c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36637847/

相关文章:

c++ - qt exe文件不运行

c++ - 如何制作一个采用 2 个参数而不是 1 个参数的递归 lambda 函数?

C++ 如何使用 std::bind/std::function 引用模板函数

c++ - 再次: why cannot static member variables be declared inline?

c++ - 我如何将 C++ 对象传递给具有不同 _ITERATOR_DEBUG_LEVEL 的 DLL

c++ - 在ifstreams中使用seekg保持有效位置

c++ - std::bind 参数到没有对象的成员函数

c++ - 将 std::function 与模板一起使用

c++ - 带有函数类型参数的 C++ 模板的语法

c++ - 对 "class"的引用不明确