Search code examples
c++templatesc++17template-meta-programmingboost-hana

Iterate over template int


I have a function:

template<class Real, int N>
constexpr std::array<Real, N> get_array();

and I would like to test it over many types and many integers. In pseudocode:

auto types = {float, double, long double};
for(int i = 0; i < 25; ++i) {
   for (type : types) {
        auto arr = get_array<type, i>();
        // test arr
   }
}

Obviously this doesn't compile. Is there a way to patch up the loop to make it so I can iterate over the array?


Solution

  • Since you have Boost.Hana tagged anyway, we can just use it:

    auto types = hana::tuple_t<float, double, long double>;
    hana::for_each(types, [](auto type){
        hana::for_each(std::make_index_sequence<25>(), [=](auto idx){
            // here type is an object that denotes the type and
            // idx is an integral constant that denotes the next value
    
            get_array<typename decltype(type)::type, idx>();
        });
    });