Create a tuple with a variable type wrapped

Today I am trying to create a tuple a bit specific (at least for me) and at compile time.

I have a basic structure, say:

struct Foo1 { int data; };
struct Foo2 { int data; };
struct Foo3 { int data; };

And one more structure, but with some template materials:

template < typename T,
           size_t Size >
struct Metadata {

  using type = T;

  std::bitset<Size>  bitset;
};

So now I want to create this type of tuple:

constexpr std::tuple<Metadata<Foo1, 3>, Metadata<Foo2, 3>, Metadata<Foo3, 3>> test { {0}, {0}, {0}};

But in an automatic way, for example:

template < typename ... Ts >
constexpr auto make_metadata() {

  return std::tuple<Metadata<Foo1, sizeof...(Ts)>, 
                    Metadata<Foo2, sizeof...(Ts)>,
                    Metadata<Foo3, sizeof...(Ts)>>{{0},{0},{0}};
}

Well, the last code is far from good, so I would like to have something similar, but automatically. Perhaps with tuple_cat and expression folding, but I lost a little. So if anyone knows the answer :)

+4
source share
3 answers

... . Ts :

template <class... Ts>
constexpr auto make_metadata()
{
    return std::make_tuple(Metadata<Ts, sizeof...(Ts)>{0}...);
}

, , :

template <class... Ts>
constexpr auto make_metadata()
{
    constexpr size_t N = sizeof...(Ts);
    return std::make_tuple(Metadata<Ts, N>{0}...);
}
+3

std::make_tuple :

template <typename... Ts>
constexpr auto make_metadata() {
    return std::make_tuple(Metadata<Ts, sizeof...(Ts)>{0}...);
}
+2

The following should do what you want:

template <typename T> struct tag {};

template <typename ... Ts>
constexpr auto make_metadata() {

  return std::tuple<Metadata<Ts, sizeof...(Ts)>...>{{(tag<Ts>{}, 0)}...};
}
+1
source

Source: https://habr.com/ru/post/1666416/


All Articles