Search code examples
c++boostboost-hana

Look for a value inside a set


I have the following code:

auto mySet = hana::make_set(2, "hi", 3.0);

How do I get the value a particular type?:

std::cout << mySet[???] << std::endl;

Like 'mySet[char*]' or something. Does set work for this, or must I use a map?


Solution

  • You must use a map. If you think of it in different terms, what you really seem to want is a std::unordered_map<Type, Object> (i.e. the keys are types and the values are, well, values). Instead, what you did is use std::unordered_set<Object>, where the keys are the same as the values.

    So instead, you should write

    auto myMap = hana::make_map(
        hana::make_pair(hana::type_c<int>, 2),
        hana::make_pair(hana::type_c<char const*>, "hi"),
        hana::make_pair(hana::type_c<double>, 3.0)
    );
    std::cout << myMap[hana::type_c<char const*>] << std::endl;
    

    Otherwise, you can also use a set and then find your element in it using hana::find_if with a predicate that would check the type of the object. But this is going to be less compile-time efficient, because hana::find_if must do a linear search.