如何实现is_pointer? [英] how to implement is_pointer?

查看:194
本文介绍了如何实现is_pointer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现is_pointer。我想要这样的:

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

推荐答案

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注意到:

Johannes noted:

这实际上缺少T * const,T * volatile和T * const volatile的特殊化。

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

解决方案:

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;
}

...但当然这只是重新创建 std :: type_traits wheel,或多或少:)

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

这篇关于如何实现is_pointer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆