How to get the template parameter of the template template?

Suppose it std::vectordoes not value_type. Can I write a template for output value_type? Or more general, given T<X>how I can infer X?

Very naive ..

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

will probably make someone who knows a little about templates laugh at my stupid attempt and when this way is created:

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

create the following errors:

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

EDIT: the first is easy to fix, but fixing it will not affect others ...

PS: I think that I have a slight misunderstanding, since it is std::vector<int>not a template, but a specific type. However, I still would like to know whether there is a way to get intby someTemplate<int>with the help of the template magic.

+4
1

:

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

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

// ...
+5

Source: https://habr.com/ru/post/1682228/


All Articles