简体   繁体   中英

Generic visitor using variadic templates

I've have small code bellow:

#include <iostream>
#include <boost/variant.hpp>
#include <functional>

struct Test
{
        void one() const { std::cout << "one\n"; }
        void two(int i) const { std::cout << "two\n"; }
};

struct TestVisitor : public boost::static_visitor<>
{
        template<class ... Args>
        void operator()( const std::function<void (Args...)>& func) const
        {
            //func(args...);
        }
};

int main() 
{ 
    Test test;
    std::function<void ()> f = std::bind(&Test::one, &test);  

    typedef boost::variant< std::function<void ()>, std::function<void (int)> > fvariant;
    fvariant var = f;
    boost::apply_visitor( TestVisitor(), var );

    return 0;
}

It would be nice to call function object "func" with variable number of arguments ( commented line ). Do you know the easiest way to implement that?

EDIT: TestVisitor is not final. Feel free to modify it in order to apply parameter pack of Args... to std::function call.

This answer may help you for applying a function to a parameter pack

How do I expand a tuple into variadic template function's arguments?

I posted a lot on this on my blog, I played around with it for a day or two, if you need more, I can post my code: Variadic Template Treatise

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM