制作一个std :: funtion如果我有两个功能

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

指向两个函数C++

制作一个std :: funtion如果我有两个功能</p> <pre><code>void foo() { std::cout << 1 << std::endl; } void bar() { std::cout << 2 << std::endl; } </code></pre> <p>指向两个函数C++

问题描述:

,我有一个函数指针制作一个std :: funtion如果我有两个功能</p> <pre><code>void foo() { std::cout << 1 << std::endl; } void bar() { std::cout << 2 << std::endl; } </code></pre> <p>指向两个函数C++

std::function<void()> v; 

,我想v()打印

1 
2 
+3

使用lambda?你的问题是什么? – hyde

+1

@hyde这样就是'[](){foo(); bar();}'对吗? – Julian

+0

如果返回类型是* not *'void',你会期望什么? – o11c

std::function对目标的定义是const T* target() const,这意味着它只能存储一个t ARGET。

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

有几个可能的解决方案:

  1. 第一种方法是使用lambda或其他功能来定义手动组播:

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

  3. 第三种选择是简单地包裹vector反正(警告:pseudocodeish):

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

您可能希望'target'是通过value或const ref引用的,因此它可以绑定到lambda表达式 –