如何获取模板模板参数的模板参数?

how to get template parameter of a template template parameter?

假设 std::vector 没有 value_type。是否可以编写一个模板来推断 value_type?或者更一般地说,给定一个 T<X>,我如何推断 X?

一个很天真的..

template <template <typename X> T>
void test(T<X> t) { 
     X x;
}

可能会让任何对模板有所了解的人都嘲笑我愚蠢的尝试,当像这样实例化时:

int main() {
    std::vector<int> x;
    test(x);
}

产生以下错误:

error: expected ‘class’ before ‘T’
 template < template<typename X> T>
                                 ^
error: ‘X’ was not declared in this scope
 void test(T<X> u) {
             ^
error: template argument 1 is invalid
 void test(T<X> u) {
              ^
In function ‘void test(int)’:
error: ‘X’ was not declared in this scope
   X x;
   ^
error: expected ‘;’ before ‘x’
   X x;
     ^
In function ‘int main()’:
error: no matching function for call to ‘test(std::vector<int>&)’
   test(x);
         ^
note: candidate is:
note: template<template<class X> class T> void test(int)
 void test(T<X> u) {
      ^
note:   template argument deduction/substitution failed:
note:   cannot convert ‘x’ (type ‘std::vector<int>’) to type ‘int’

编辑:第一个很容易修复,但修复它不会影响其他...

PS:我想我有个小误会,std::vector<int>不是模板,而是具体类型。但是,我仍然想知道是否有办法使用一些模板魔法从 someTemplate<int> 中获取 int

您可以创建一个特征来提取这些参数:

template <typename T> struct first_param;

template <template <typename, typename...> class C, typename T, typename ...Ts>
struct first_param<C<T, Ts...>>
{
    using type = T;
};

对于 C++11 之前的版本,您必须处理参数数量直到可接受的值:

template <typename T> struct first_param;

template <template <typename> class C, typename T>
struct first_param<C<T>>
{
    typedef T type;
};

template <template <typename, typename> class C, typename T, typename T2>
struct first_param<C<T, T2>>
{
    typedef T type;
};

template <template <typename, typename, typename> class C,
          typename T, typename T2, typename T3>
struct first_param<C<T, T2, T3>>
{
    typedef T type;
};

// ...