philipp
philipp

Reputation: 1823

Template Parameter Pack: How to create a Tuple of an independent type with same length

My question is about parameter packs and related tuples. How can I create a tuple of the same size as the parameter pack, but with a single independent type?

template <class... T>
class Thing {
  public:
    // some struct that was found helpful for any Type used as parameter
    struct HelperData{ 
      int a; 
      int b; 
    };

    [...]

  private:
    // the tuple used as normally, my initial reason to use parameter pack
    std::tuple<T...> m_tuple;

    // now I want a tuple of N values of type HelperData, where N is sizeof...(T)
    std::tuple<HelperData...sizeof...(T)> m_helperData; //???
};

Retrospective Comment:

This question might be technically valid and has great answers. But the underlying concept brought up more and more questions (how to iterate over multiple containers at once, etc). It might be the right thing to to with C++14 or newer, however, I just found out that with C++11, things are substantially easier when I just work around the problem:

I have a list of types/objects, represented by the parameter pack. This defines the main tuple as a class member. Now I want additional information, for each of these types/objects, stored in an additional tuple. Don't do that. This structure can (almost) always be replaced by a single tuple, containing e.g. structs with all the elements which are otherwise spread across multiple tuples.

Upvotes: 2

Views: 843

Answers (2)

Caleth
Caleth

Reputation: 63362

Does it need to be std::tuple or would something else you can std::get work?

std::array<HelperData, sizeof...(T)> m_helperData;

Upvotes: 3

Quentin
Quentin

Reputation: 63174

You need to hook onto the parameter pack to enable expansion, then ignore it:

// ...

template <class T, class>
using hook = T;

std::tuple<hook<HelperData, T>...> m_helperData;

Upvotes: 6

Related Questions