Vector of std::function with different signatures

前端 未结 7 1750
离开以前
离开以前 2020-12-03 03:32

I have a number of callback functions with different signatures. Ideally, I would like to put these in a vector and call the appropriate one depending on certain conditions.

相关标签:
7条回答
  • 2020-12-03 04:32

    What you want is possible through polymorphism. The idea is to create a class with a specific signature, which at runtime will call different methods. For example:

    #include <iostream>
    #include <functional>
    #include <memory>
    #include <vector>
    
    void foo(int) {
        std::cout << "I'm foo!\n";
    }
    
    int bar(char, double) {
        std::cout << "I'm bar!\n";
    }
    
    class MyFunction {
        public:
            virtual ~MyFunction(){}
    
            virtual void operator()() = 0;
    };
    
    class MyFunctionA : public MyFunction {
        public:
            virtual void operator()() {
                foo(4);
            }
    };
    
    class MyFunctionB : public MyFunction {
        public:
            MyFunctionB(std::function<int(char,double)> f, char arg1, double arg2) : fun_(f), arg1_(arg1), arg2_(arg2) {} 
    
            virtual void operator()() {
                fun_(arg1_, arg2_);
            }
        private:
            std::function<int(char,double)> fun_;
            char arg1_;
            double arg2_;
    };
    
    int main() {
        using MyFunPtr = std::unique_ptr<MyFunction>;
        std::vector<MyFunPtr> v;
    
        v.emplace_back(new MyFunctionA());
        v.emplace_back(new MyFunctionB(bar, 'c', 3.4));
    
        for ( auto&& myfun : v ) {
            (*myfun)();
        }
        return 0;
    }
    

    You can make the derived classes as complicated as you need be, but since in the end they all have the same interface you will be able to call all of them.

    0 讨论(0)
提交回复
热议问题