template 模板参数推导与 C++ class templates

template template parameter deduction with C++ class templates

有没有办法在没有部分模板特化的情况下确定 class 模板化的模板参数的模板参数,假设 class 只能用模板模板化本身就是模板的参数?

为了使事情具体化,这里有一个例子:

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>>
}

正是针对这种情况,标准容器公开了一个 value_type 成员,例如:

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

否则,您可以使用一个单独的帮助程序,它利用 模板模板参数 模板参数推导 来确定值类型是什么,例如:

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

或者:

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