Robin Lew
Robin Lew

Reputation: 483

How to use template to generate a regular argument list and pass it to run time functions?

For example, I want to generate a reverse ordered array, but the codes are really redundant. The constructor is on run-time but the array size is on compile time. However, these codes are very similar.

#include <array>
#include <cstdint>
using std::array;
array<int32_t, 5> genReverse5() {
  array<int32_t, 5> a{5, 4, 3, 2, 1};
  return a;
}

array<int32_t, 4> genReverse4() {
  array<int32_t, 4> a{ 4, 3, 2, 1};
  return a;
}

array<int32_t, 3> genReverse3() {
  array<int32_t, 3> a{ 3, 2, 1};
  return a;
}

Upvotes: 2

Views: 38

Answers (1)

songyuanyao
songyuanyao

Reputation: 172894

You can try with std::integer_sequence (since C++14).

template <std::size_t... I>
auto genReverse_impl(std::index_sequence<I...>) {
  array<int32_t, sizeof...(I)> a{ (sizeof...(I) - I)... }; // decrease progressively
  return a;
}
template<std::size_t N, typename Indices = std::make_index_sequence<N>>
auto genReverse()
{
  return genReverse_impl(Indices{});
}

then use it as

genReverse<5>(); // returns array initialized as {5, 4, 3, 2, 1}
genReverse<4>(); // returns array initialized as {4, 3, 2, 1}
genReverse<3>(); // returns array initialized as {3, 2, 1}

LIVE

Upvotes: 3

Related Questions