Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement is_pointer?

Tags:

c++

templates

I want to implement is_pointer. I want something like this:

template <typename T >
bool is_pointer( T t )
{
   // implementation
} // return true or false

int a;
char *c;
SomeClass sc;
someAnotherClass *sac;

is_pointer( a ); // return false

is_pointer( c ); // return true

is_pointer( sc ); // return false

is_pointer( sac ); // return true

How can I implement it? Thanks

like image 515
Davit Siradeghyan Avatar asked Jul 05 '10 07:07

Davit Siradeghyan


Video Answer


1 Answers

template <typename T>
struct is_pointer_type
{
    enum { value = false };
};

template <typename T>
struct is_pointer_type<T*>
{
    enum { value = true };
};

template <typename T>
bool is_pointer(const T&)
{
    return is_pointer_type<T>::value;
}

Johannes noted:

This is actually missing specializations for T *const, T *volatile and T * const volatile i think.

Solution:

template <typename T>
struct remove_const
{
    typedef T type;
};

template <typename T>
struct remove_const<const T>
{
    typedef T type;
};

template <typename T>
struct remove_volatile
{
    typedef T type;
};

template <typename T>
struct remove_volatile<volatile T>
{
    typedef T type;
};

template <typename T>
struct remove_cv : remove_const<typename remove_volatile<T>::type> {};

template <typename T>
struct is_unqualified_pointer
{
    enum { value = false };
};

template <typename T>
struct is_unqualified_pointer<T*>
{
    enum { value = true };
};

template <typename T>
struct is_pointer_type : is_unqualified_pointer<typename remove_cv<T>::type> {};

template <typename T>
bool is_pointer(const T&)
{
    return is_pointer_type<T>::value;
}

...but of course this is just reinventing the std::type_traits wheel, more or less :)

like image 80
fredoverflow Avatar answered Sep 21 '22 06:09

fredoverflow