How to achieve dynamic polymorphism (run-time call dispatch) on unrelated types?

后端 未结 4 531
说谎
说谎 2021-02-01 23:50

GOAL:

I would like to achieve type-safe dynamic polymorphism (i.e. run-time dispatch of a function call) on unrelated types

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-02 00:14

    OK, here's a wild shot:

    template 
    struct visitor : boost::static_visitor
    {
        template 
        R operator()(T & x)
        { 
            return tuple_unpack(x, t);   // this needs a bit of code
        }
    
        visitor(Args const &... args) : t(args...) { }
    
    private:
        std::tuple t;
    };
    
    template 
    R call_on_variant(Var & var, Args const &... args)
    {
        return boost::apply_visitor(visitor(args...), var);
    }
    

    Usage:

    R result = call_on_variant(my_var, 12, "Hello", true);
    

    I've hidden a certain amount of work you need for calling a function by unpacking a tuple, but I believe this has been done elsewhere on SO.

    Also, if you need to store references rather than copies of the arguments, this can possibly be done, but needs more care. (You can have a tuple of references. But you have to think about whether you also want to allow temporary objects.)

提交回复
热议问题