简体   繁体   中英

get first template parameter of a class

I have a class foo which takes two template parameters, what I want to do is defaulting the second parameter to the first template parameter of the first parameter if it exists. foo would look like

template<typename Class, typename T = typename first_template_parameter<Class>::type>
class foo
{
   ...
}

and if Class has been defined as template<typename A, typename B, ...> class bar I want T to be A . So for example foo<std::map<int, float>> would have Class = std::map<int, float> and T = int , foo<int, char> would have Class = int and T = char . How can I implement first_template_parameter ?

Drilling down into the first template parameter requires a little bit of work involving specialization:

template<typename T> struct first_template_type;

template<template<typename T, typename ...> class t,
     typename T, typename ...Args>
struct first_template_type<t<T, Args...>> {
    typedef T type_t;
};

template<typename T>
using first_template_type_t=typename first_template_type<T>::type_t;

Once that's out of the way, the rest is pretty boring:

#include <map>

template<typename Class,
     typename T = first_template_type_t<Class>>
class foo
{
public:
    T bar;
};

foo<std::map<int, char>> Foo;

int *baz=&Foo.bar;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM