C++ std::function variable with varying arguments

后端 未结 6 1495
天涯浪人
天涯浪人 2020-12-28 09:12

In my callback system I want to store std::function (or something else) with varying arguments.

Example:

  1. I want to call void()
6条回答
  •  无人及你
    2020-12-28 09:55

    The following solution might work for you (I'm not sure that the code is absolutely correct here):

    Create a wrapper for std::function with virtual destructor to enable using dynamic cast

    class function_wrapper_base
    {
        virtual ~function_wrapper_base();
    }
    
    template 
    class function_wrapper
        : public function_wrapper_base
    {
    public:
       std::function f;
       ...
    };
    

    Then create a class variant_function_holder

    class variant_function_holder
    {
        std::unique_ptr f;
        ...
        template 
        void operator()(Args&&... args)
        {
            function_wrapper::type...> * g = dynamic_cast::type...>>(f.get());
    
            if (g == nullptr)
            {
                // ToDo
            }
    
            g->f(std::forward(args)...);
        }
    };
    

提交回复
热议问题