2015-01-21 29 views
2

假設我有類從模板類獲得一個「子類型」

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

回答

5

只需在課堂上使用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; 
}; 
4

你也可以寫一元函數把它拉出來:

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;