Container for different functions?

后端 未结 1 1547
感动是毒
感动是毒 2021-02-14 14:29

I\'m trying to implement a container class for different functions where I can hold function pointers and use it to call those functions later. I\'ll try to discribe my problem

相关标签:
1条回答
  • 2021-02-14 15:10

    You may do something like:

    class BaseFunc {
    public:
        virtual ~BaseFunc() = default;
    
        virtual void Call(std::vector<boost::variant<int, double>>& args_vec) const = 0;
    };
    
    template <typename F> class Function;
    
    template <typename R, typename... Args> class Function<R(Args...)> : public BaseFunc
    {
    public:
        Function(R (*f)(Args...)) : f(f) {}
        void Call(std::vector<boost::variant<int, double>>& args_vec) const override
        {
            Call(args_vec, std::index_sequence_for<Args...>());
        }
    private:
        template <std::size_t ... Is>
        void Call(
            std::vector<boost::variant<int, double>>& args_vec,
            std::index_sequence<Is...>) const
        {
            // Add additional check here if you want.
            f(boost::get<Args>(args_vec.at(Is))...);
        }
    
    private:
        R (*f)(Args...);
    };
    

    Live example

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