Get decltype of template argument

I often want to get the decltype argument of a class template argument so that I can use it further, for example, in a loop that I split and simplified to show my problem:

template <typename T>
class Foo {
public:
    T type; //This is my hack to get decltype of T
};

template <typename T>
class Bar {
public:

};

int main() {
    for(auto& foo : fs) {
        //Is there some way to get the decltype of the template without having to refer to some arbitrary T member of Foo?
        auto bar = someFunction<decltype(foo.type)>();
    }
}

Is there a way to get the decltype of a template argument without doing this hack? If not, what is the best workaround to get a value like that value?

+4
source share
2 answers

You can create type_traits:

template <typename C>
struct get_template_type;

template <template <typename > class C, typename T>
struct get_template_type<C<T>>
{
    using type = T;
};

and then you use it (provided C = Foo<T>you have T)

typename get_template_type<C>::type

Living example

EDIT . For classes with several template parameters to get the first:

template <template <typename > class C, typename T, typename ... Ts>
struct get_template_type<C<T, Ts...>>
{
    using type = T;
};
+6
source

EVerything - typedefs:

template<typename T>
struct Bla
{ using value_type = T; }

, :

template<typename T>
void f(const T& t)
{
  typename T::value_type some_var_with_template_type;
}

:

template<template<typename> class Class, typename T>
void f(const Class<T>& c)
{
  T some_var_with_template_type;
}

. , Class , ( ). Variadic:

template<template<typename, typename...> class Class, typename T, typename... ArgTypes>
void f(const Class<T, ArgTypes...>& t)
{
  T some_var_of_template_type;
}

, value_type typedef .

, , .

+1

All Articles