P45 Imminent
P45 Imminent

Reputation: 8591

Getting a "sub-type" from a template class

Suppose I have the class

template<
    typename T1, /*this is probably an integral type*/
    T1 Default /*this is a typical value of that integral type*/
> class Foo {};

and an instantiation of this for a given T1 and Default, say foo.

I can use decltype(foo) to get the complete type.

Is there some syntax I can use to get the value Default?

Upvotes: 2

Views: 130

Answers (2)

Barry
Barry

Reputation: 303087

You can also write a metafunction to pull it out:

template <typename T> struct my_trait;

template <typename T, T Value>
struct my_trait<Foo<T, Value>>
{
    using T1 = T;
    static const T1 Default = Value;
};

Used thusly:

Foo<int, 42> myfoo;
std::cout << "Default is " << my_trait<decltype(myfoo)>::Default;

Upvotes: 4

ForEveR
ForEveR

Reputation: 55887

Just use typedef in class.

template<
    typename T1,
    typename T2
> class Foo 
{
public:
   typedef T1 type1;
   typedef T2 type2;
};

To get default you can use actually the same syntax.

template<
    typename T1,
    T1 Default
> class Foo 
{
public:
   typedef T1 type1;
   static constexpr const T1 default_value = Default;
};

Upvotes: 5

Related Questions