如果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
類的工作在兩個迭代器和指針。
在迭代器上做這個工作嗎? – smerlin 2010-06-17 06:32:12
使用迭代器解決方案來獲得更通用的方法。它將與指針一起工作。 – GManNickG 2010-06-17 06:40:27
我編輯了我的答案,以包含適用於迭代器的解決方案。 – 2010-06-17 06:54:05