I have this class
class Store
{
template <int N> using map = std::unordered_map<typename Topo<N>::type*, std::unique_ptr<Node<N>>>;
template <int N> map<N>& get();
map<0> m_0;
template <> map<0>& get<0>() { return m_0; }
map<1> m_1;
template <> map<1>& get<1>() { return m_1; }
// ...
map<7> m_7;
template <> map<7>& get<7>() { return m_7; }
};
I am looking for a way to avoid to repeat the declaration of the variables. Probably it is possible to do something with integer sequences, but I cannot figure out the syntax.
CodePudding user response:
As suggested by HolyBlackCat, you can use std::make_index_sequence
to declare a std::tuple< map<0> , map<1> ,... map<N>>
. You do not need getters. When they return non-const references you can make the members public.
#include <memory>
#include <tuple>
#include <utility>
template <int N> struct Foo {};
template <typename X> struct foo_tuple_impl;
template <int...I> struct foo_tuple_impl< std::integer_sequence<int,I...> > {
using type = std::tuple< Foo<I> ...>;
};
template <int N> struct foo_tuple {
using type = typename foo_tuple_impl< std::make_integer_sequence<int,N> >::type;
};
template <int N> using foo_tuple_t = typename foo_tuple<N>::type;
struct Storage {
foo_tuple_t<7> map;
};
CodePudding user response:
How about putting them in a heterogeneous array (i.e. tuple)?
class Store
{
public:
template <int N> using map = std::unordered_map<typename Topo<N>::type*, std::unique_ptr<Node<N>>>;
template <int N> map<N>& get();
std::tuple<map<0>, map<1>, ..., map<7>> maps;
};
Store store;
auto& m_1 = std::get<1>(store.maps);
...
You can have a getter if you want:
template<int N>
const auto& get_map() const {
return std::get<N>(maps);
}