How to get a tuple based on list of template templates of variable size in C++?

Hi All,

I have created a template class which takes two plain template parameters (like int or double) and have derived several other classes from it:

template <typename A, typename B>
class IClassBase {...}

template <typename B>
class Derived1Class : public IClassBase<std::string, B> {...}

template <typename B>
class Derived2Class : public IClassBase<std::string, B> {...}

I need to design a structure which would allow compiler to build a std::tuple based on list of template types and their parameters (B type in code snippet above).

So given the list below

Derived1Class<int>, Derived1Class<double>, Derived2Class<bool>, Derived2Class<std::string>

compiler should infer following tuple:

std::tuple<int, double, bool, std::string>

Is this even possible, and if so, how it can be done in C++?

Thanks in advance)
Possible. A template specialization can be used to infer the type.

1
2
3
4
5
6
7
template <typename T>
struct First {};
template <template <typename...> class T,
	  typename Arg, typename... Rest>
struct First<T <Arg, Rest...>> {
  using type = Arg;
};


And then building the tuple is as easy as iterating over a parameter pack:

1
2
3
4
template <typename... Args>
struct TupleFromFirst {
  using type = std::tuple <typename First <Args>::type...>;
};


A test:
1
2
3
4
5
6
7
static_assert (std::is_same
                <std::tuple<int, double, bool, std::string>,
                 TupleFromFirst <Derived1Class<int>,
                                 Derived1Class<double>,
                                 Derived2Class<bool>,
                                 Derived2Class<std::string>>::type
                >::value, "same type");
Last edited on
A less sophisticated approach ...
1
2
3
4
5
6
7
8
9
10

vector<Derived1Class<int>> v1;
vector<Derived1Class<double>> v2;
vector<Derived2Class<bool>> v3;
vector<Derived2Class<string>> v4;

for (size_t i = 0; i < v1.size(); i++)//assuming all vectors have same size or could also use min(v1.size(), ..., v4.size())//
{
	make_tuple(v1[i], v2[i], v3[i], v4[i]);
}

You can also make_tuple in situ into a container of the correct type directly with emplace_back or an iterator adaptor
Topic archived. No new replies allowed.