Home > Back-end >  template template parameter deduction with C class templates
template template parameter deduction with C class templates

Time:03-17

Is there a way, without partial template specialization, to determine the template parameter of a template parameter that a class is templatized with, assuming that a class can only be templatized with a template parameter that itself is a template?

To make things concrete, here's an example:

template <typename T>
struct A {
// Needed: a function to print the size of the template parameter
// that "T" is templatized with, e.g. "char" in the example
// below
};

template <typename A>
struct X{}

int main() {
  A<X<char>>
}

CodePudding user response:

It is for situations like this why standard containers expose a value_type member, eg:

template <class T>
struct A {
    // Needed: a function to print the size of the template parameter
    // that "T" is templatized with, e.g. "char" in the example
    // below
    void printSize() const { cout << sizeof(typename T::value_type); }
};

template <typename A>
struct X {
    using value_type = A;
};

Online Demo

Otherwise, you can use a separate helper that utilizes a template template parameter and template argument deduction to determine what the value type is, eg:

template<template<class, class...> class C, class T, class... OtherTs>
size_t A_helper_printSize(C<T, OtherTs...>&&) { return sizeof(T); }

template <class T>
struct A {
    // Needed: a function to print the size of the template parameter
    // that "T" is templatized with, e.g. "char" in the example
    // below
    void printSize() const { cout << A_helper_printSize(T{}); }
};

Online Demo

Alternatively:

template<template<class, class...> class C, class T, class... OtherTs>
T A_helper_valueType(C<T, OtherTs...>&&);

template <class T>
struct A {
    // Needed: a function to print the size of the template parameter
    // that "T" is templatized with, e.g. "char" in the example
    // below
    void printSize() const { cout << sizeof(decltype(A_helper_valueType(std::declval<T>()))); }
};

Online Demo

  • Related