Reputation: 377
Is it possible to make macro that expand tuple parameters depending on N? Like we need tuple with "3 int". So we just write m(3) which becomes "int, int, int"
const int k = 3;
#define m(N) int, int, int //how to write int, int, int here in cycle?
typedef std::tuple<m(k)> new_type;
Is there maybe another way to do this?
Upvotes: 0
Views: 312
Reputation: 217085
Whereas you can do some REPEAT MACRO (which would forward to REPEAT_3, REPEAT_2 and REPEAT_1) and would have some hard coded limit,
you might use instead template for the generation, for example:
template <typename T, std::size_t> using always_t = T;
template <typename T, typename Seq> struct gen_tuple_helper;
template <typename T, std::size_t ... Is>
struct gen_tuple_helper
{
using type = std::tuple<always_t<T, Is>...>;
};
template <typename T, std::size_t N>
using gen_tuple_t = typename gen_tuple_helper<T, std::make_index_sequence<T>>::type;
static_assert(std::is_same_v<std::tuple<int, int, int>, gen_tuple_t<int, 3>>);
Note: As noted in comment homogeneous std::tuple
might be replaced by std::array
which seems simpler to manipulate.
Upvotes: 1
Reputation: 20918
You can define function which returns a tuple with given T
type repetead N
times:
template<class T, size_t ... indices>
auto helper(std::index_sequence<indices...>) {
return std::tuple_cat( (indices,std::tuple<T>())... );
}
template<class T, size_t N>
auto genTuple() {
return helper<T>(std::make_index_sequence<N>{});
}
Then, define alias template taking type and number of reps:
template<class T, size_t N>
using Tuple = decltype(genTuple<T,N>());
by decltype you get return type of function - your desired tuple.
Usage:
Tuple<int,3> t;
Upvotes: 1