繁体   English   中英

从模板类中获取“子类型”

[英]Getting a “sub-type” from a template class

假设我有班级

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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