2013-05-03 81 views
0

繼承我要代表這樣一個層次結構:CRTP從其默認實例

template<typename T> 
struct X 
{ 
}; 

template<typename Derived = void> 
struct Y : Y<void> 
{ 
    //Note: not trying to use SFINAE here 
    using DerivedType = typename std::enable_if<std::is_base_of<Y, Derived>::value, Derived>::type; 
}; 
template<> 
struct Y<void> : X<Y<void>> 
{ 
}; 

struct Z : Y<Z> 
{ 
}; 

兩個Z和Y <無效>需要被實例化:

W<Y<>> wy; 
W<Z> wz; 

全部▲<牛逼>需要成爲Y <void>的實例,如果可能的話,我寧願不使用兩個不同的名稱來使其工作。 (這是我的最後手段)

問題是,我不知道如何使這項工作。上面的代碼顯然不能按預期工作,也不會編譯。有沒有一種方法可以使其發揮作用,或者除了我已經提到的方法之外,您是否還有其他方法的建議?

+0

你到底想達到什麼目的? 'std :: enable_if'不會觸發SFINAE,而是一個硬錯誤。與'static_assert(std :: is_base_of :: value)'' – 2013-05-03 16:54:35

+0

沒有太大差別我不想在這裏使用SFINAE,它應該會觸發一個硬錯誤。 – 2013-05-03 18:06:38

+0

然後,如果它被聲明爲'static_assert',它會更清晰:)從編譯器的角度來看效果將是相同的,但對其他維護者來說更清楚。 – 2013-05-03 18:19:43

回答

3

如何重新安排它:

template <typename> struct Y; 

template <> struct Y<void> : X<Y<void>> { }; 

template <typename T = void> struct Y : Y<void> { }; 
+0

謝謝,這很有效!我對你的答案進行了更正,因爲你繼承了錯誤的東西並且保持默認值 – 2013-05-03 18:13:03

+0

@ LB--:哦好的,我明白了,現在我添加了這些更改。 – 2013-05-03 19:41:35