Если 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
может быть итератором или указателем , вам необходим класс iterator_traits
, который является частью стандартной библиотеки. В вашем случае это используется так:
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
работает как с итераторами, так и с указателями.