Dima Redko Dima Redko - 1 year ago 127
C++ Question

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

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)

Answer Source

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

Anything is possible in C++. Especially the current C++ standard. Tested with gcc 6.2.

#include <tuple>
#include <string>

template<typename template_type> class extract_param;

template<template<typename T> typename template_param, typename template_param_t>
class extract_param<template_param<template_param_t>> {

    typedef template_param_t type_t;

template<typename ...Args>
using extract_tuple=std::tuple<typename extract_param<Args>::type_t...>;

template<typename T> class sometemplate {};

int main()
    extract_tuple< sometemplate<int>, sometemplate<std::string>> tuple;

    int &intref=std::get<0>(tuple);
    std::string &stringref=std::get<1>(tuple);

    return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download