0

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?

DBenson
  • 377
  • 3
  • 12
  • 2
    Macros are considered bad practice for [some reasons](https://stackoverflow.com/questions/14041453/why-are-preprocessor-macros-evil-and-what-are-the-alternatives). If your tuple only consists of `int`, why not simply use a `std::array`? – Lukas-T Apr 11 '20 at 09:37
  • You can indeed make MACRO for that, but you will be limited by hard-coded limit. template seems more appropriate. – Jarod42 Apr 11 '20 at 10:26

2 Answers2

1

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;

Live demo

rafix07
  • 20,001
  • 3
  • 20
  • 33
1

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.

Jarod42
  • 203,559
  • 14
  • 181
  • 302