2010-06-17 17 views
2

有沒有辦法獲得類模板參數的防禦類型?如何獲取延遲模板參數的類型

template <class TPtr> 
struct foo { 
    typedef TPtr ptr_type; 
    typedef ??? element_type; /* shall be the type of a deferred TPtr*/ 
}; 

所以foo<const char*>::element_type結果const char,並foo<std::vector<int>::iterator_type>::element_type結果int

我知道我可以使用value_type typedef爲C++迭代器(如std::vector<int>::iterator_type::value_type),但原始指針沒有得到value_type typedef,所以我在這裏運氣不好。

回答

4

如果TPtr只能是指針,您正在尋找Boost's remove_pointer

如果你想知道如何在工作的世界,它採用以這種方式局部專業化:

template<typename T> 
struct RemovePointer; 

template<typename T> 
struct RemovePointer<T*> 
{ 
    typedef T Type; 
}; 

int main() 
{ 
    RemovePointer<int*>::Type foobar; // foobar has the type int 
    return 0; 
} 

如果TPtr可以是一個迭代或指針,則需要the iterator_traits class,這是標準庫的一部分。根據你的情況,它的使用是這樣的:

template <class TPtr> 
struct foo { 
    typedef TPtr ptr_type; 
    // The compiler won't know for sure if value_type is actually 
    // a type until TPtr is known. The typename keyword is a hint 
    // to the compiler so it doesn't cause an error. 
    typedef typename iterator_traits<TPtr>::value_type element_type; 
}; 

不管你信不信,它的工作原理是局部特殊化爲好。它基本上是這樣定義的:

// Primary template for iterators 

template<class Iterator> 
struct iterator_traits 
{ 
    typedef typename Iterator::difference_type difference_type; 
    typedef typename Iterator::value_type value_type; 
    typedef typename Iterator::pointer pointer; 
    typedef typename Iterator::reference reference; 
    typedef typename Iterator::iterator_category iterator_category; 
}; 

// Partial specializations for pointers 

template<class T> 
struct iterator_traits<T*> 
{ 
    typedef ptrdiff_t difference_type; 
    typedef T value_type; 
    typedef T* pointer; 
    typedef T& reference; 
    typedef random_access_iterator_tag iterator_category; 
}; 

template<class T> 
struct iterator_traits<const T*> 
{ 
    typedef ptrdiff_t difference_type; 
    typedef T value_type; 
    typedef const T* pointer; 
    typedef const T& reference; 
    typedef random_access_iterator_tag iterator_category; 
}; 

這就是爲什麼iterator_traits類的工作在兩個迭代器和指針。

+0

在迭代器上做這個工作嗎? – smerlin 2010-06-17 06:32:12

+0

使用迭代器解決方案來獲得更通用的方法。它將與指針一起工作。 – GManNickG 2010-06-17 06:40:27

+0

我編輯了我的答案,以包含適用於迭代器的解決方案。 – 2010-06-17 06:54:05