Search code examples
c++template-meta-programmingboost-fusion

Collect all boost fusion map keys into a std::tuple


Consider this snippet:

#include <boost/fusion/container/map.hpp>
#include <boost/fusion/sequence/intrinsic/at_key.hpp>
#include <boost/fusion/sequence/intrinsic/value_at_key.hpp>
#include <tuple>

struct MyEvents {
    struct EventA;
    struct EventB;
    using EventMap = boost::fusion::map<boost::fusion::pair<EventA, int>,
                                        boost::fusion::pair<EventB, double>>;
};

template <typename T>
struct GetTypes;

template <typename T>
struct GetTypes<boost::fusion::map<...>> {
    using type = std::tuple<...>;
};

int main() {
    using Map = typename MyEvents::EventMap;
    using AllKeys = GetTypes<Map>::type;

    return 0;
}

Demo

I want to collect all key types from a boost::fusion::map into a std::tuple.

The keys in this snippet are MyEvents::EventA and MyEvents::EventB, so AllKeys = std::tuple<MyEvents::EventA, MyEvents::EventB>.

How could one do this with template specialization? Do I need some kind of recursive calls?


Solution

  • You can get the key type of boost::fusion::pair by using T::first_type.

    template <typename T>
    struct GetTypes;
    
    template <typename... Pairs>
    struct GetTypes<boost::fusion::map<Pairs...>> {
        using type = std::tuple<typename Pairs::first_type...>;
    };
    

    Demo.