从模板类获取"sub-type"

Getting a "sub-type" from a template class

本文关键字:sub-type 获取      更新时间:2023-10-16

假设我有这个类

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

以及给定T1Default的实例化,例如foo.

我可以使用decltype(foo)来获取完整的类型。

是否有一些语法可以用来获取值Default

只需在课堂上使用typedef即可。

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

要获得默认值,您实际上可以使用相同的语法。

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

你也可以写一个元函数来拉出它:

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

因此使用:

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