I'm trying to use boost::hana
to create a constexpr
lookup table that gets quite big (up to 32768 elements). This is my code:
#include <boost/hana.hpp>
#include <boost/hana/assert.hpp>
namespace hana = boost::hana;
template <typename Count>
static constexpr auto createLookupTable(void)
{
auto indices = hana::make_range(hana::int_c<0>, hana::int_c<Count::value>);
return hana::unpack(indices, [](auto... index)
{
return hana::make_map(
hana::make_pair(
index,
hana::int_c<0>)...);
});
}
int main()
{
constexpr auto lookupTable = createLookupTable<std::integral_constant<unsigned, 128>>();
BOOST_HANA_CONSTANT_CHECK(hana::length(lookupTable) == hana::size_c<128>);
}
For testing purpose the value of each pair is hana::int_c<0>
. This gets replaced by something meaningful.
It takes some time to compile this. Is there a faster way to do it using hana?
Thanks
Maps are the right tool to represent a lookup table when you deal with sparse indexes or when there is no order on the keys.
Since you're dealing with contiguous integers as your lookup table keys, you really should stick to old C-style arrays, or better yet, std::array<128, your_value_type>
:
constexpr std::array<128, your_value_type> lookupTable = {
// ...
};
Once you've got this, you can delegate the construction of that table to a constexpr
templated function:
template<unsigned size>
constexpr std::array<size, your_value_type> lookupTable()
{
return /* ... */;
}
constexpr auto lookupTable = lookupTable<128>();