Home > front end >  How do I repeat template arguments a set number of times?
How do I repeat template arguments a set number of times?

Time:01-05

I'm writing a templated class, and I want to have a tuple that holds some data. The type of the tuple is related to the template arguments in this way:

template<typename ...Types>
class MyClass{
     public:
          std::tuple<int, (repeat "int" sizeof...(Types) times)> MyData;
}

For example, MyClass<int, float, std::string, double> would result in a MyData variable of type std::tuple<int, int, int, int>. I've looked into fold expressions, but I'm not sure that they can do what I want. Is there a way to do this in C , and if so, how?

CodePudding user response:

You can separate the first argument in the template parameter list.

template<typename T, typename ...Types>
class MyClass{
     public:
          std::tuple<T, T, T> MyData;
};

Link to demo

CodePudding user response:

As it says in the comments, use std::array. But, for completeness:

You can use std::conditional.

#include <string>
#include <tuple>
#include <type_traits>

template<typename ...Types>
struct TupleN { std::tuple<typename std::conditional<true, int, Types>::type...> MyData; };

static_assert(std::is_same_v<decltype(TupleN<int, float, std::string, double>::MyData),
              std::tuple<int, int, int, int>>);

You could also roll your own:

template<typename T> struct Ignore { using type = int; };
  • Related