Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 617
P45 Imminent Avatar asked Jun 08 '26 17:06

P45 Imminent


2 Answers

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;
};
like image 134
ForEveR Avatar answered Jun 11 '26 08:06

ForEveR


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;
like image 37
Barry Avatar answered Jun 11 '26 07:06

Barry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!