2011-04-02 15 views

回答

14
template <typename T> 
struct pointer_depth_impl 
{ 
    enum { value = 0 }; 
}; 

template <typename T> 
struct pointer_depth_impl<T* const volatile> 
{ 
    enum { value = pointer_depth_impl<T const volatile>::value + 1 }; 
}; 

template <typename T> 
struct pointer_depth 
{ 
    enum { value = pointer_depth_impl<T const volatile>::value }; 
}; 
+0

感謝詹姆斯,最後一句是非常有幫助了。 – user2023370 2011-04-02 08:57:23

+1

一個技巧是總是將'T const volatile'傳遞給下一個遞歸,然後只匹配''。這有點破解,但它可以避免編寫特殊的常量/易失性版本。 – 2011-04-02 11:54:47

+0

@Johannes:很好;擺脫對''的需求。我不認爲這特別危險;至少,除了許多其他類型的特徵之外,沒有更多的破解:-) – 2011-04-02 14:52:14

4

它可以通過遞歸來完成。

template<typename T> 
struct Depth 
{ 
    enum { value = 0 }; 
}; 

template<typename T> 
struct Depth<T*> 
{ 
    enum { value = Depth<T>::value + 1 }; 
}; 
+0

+1:但更喜歡使用枚舉。 – 2011-04-02 01:25:01

+0

@馬丁:的確,編輯過。 – 2011-04-02 01:31:00

+0

@Martin:你會解釋爲什麼更喜歡enum嗎? – rafak 2011-04-02 21:02:39

相關問題