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

时间:2017-07-25 13:41:39

标签: c++ templates c++98

假设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>不是模板,而是具体类型。但是,我仍然想知道是否有办法从int获取带有模板魔法的someTemplate<int>

1 个答案:

答案 0 :(得分:5)

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

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

// ...