Is it possible to iterate an mpl::vector at run time without instantiating the types in the vector?

前端 未结 6 1338
青春惊慌失措
青春惊慌失措 2020-12-25 14:27

Generally, I would use boost::mpl::for_each<>() to traverse a boost::mpl::vector, but this requires a functor with a template function declar

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-25 15:09

    Interesting question! As far as I can tell, Boost.MPL does not seem to provide such an algorithm. However, writing your own should not be too difficult using iterators.

    Here is a possible solution:

    #include 
    #include 
    #include 
    
    using namespace boost::mpl;
    
    
    namespace detail {
    
    template < typename Begin, typename End, typename F >
    struct static_for_each
    {
        static void call( )
        {
            typedef typename Begin::type currentType;
    
            F::template call< currentType >();
            static_for_each< typename next< Begin >::type, End, F >::call();
        }
    };
    
    
    template < typename End, typename F >
    struct static_for_each< End, End, F >
    {
        static void call( )
        {
        }
    };
    
    } // namespace detail
    
    
    template < typename Sequence, typename F >
    void static_for_each( )
    {
        typedef typename begin< Sequence >::type begin;
        typedef typename end< Sequence >::type   end;
    
        detail::static_for_each< begin, end, F >::call();
    }
    

    [The naming may not be very well chosen, but well...]

    Here is how you would use this algorithm:

    struct Foo
    {
        static void staticMemberFunction( )
        {
            std::cout << "Foo";
        }
    };
    
    
    struct Bar
    {
        static void staticMemberFunction( )
        {
            std::cout << "Bar";
        }
    };
    
    
    struct CallStaticMemberFunction
    {
        template < typename T >
        static void call()
        {
            T::staticMemberFunction();
        }
    };
    
    
    int main()
    {
        typedef vector< Foo, Bar > sequence;
    
        static_for_each< sequence, CallStaticMemberFunction >(); // prints "FooBar"
    }
    

提交回复
热议问题