c++ - 如何实现is_pointer?

标签 c++ templates

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

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

我该如何实现? 谢谢

最佳答案

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

约翰内斯指出:

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 轮子:)

关于c++ - 如何实现is_pointer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3177686/

相关文章:

C++ type_info 作为模板(typename)参数

c++ - 如何减少或消除通过更改 16 位 PCM 样本的 'volume' 所产生的噪音

c++ - 将线程对象放入 vector 中,其中函数是成员函数并需要返回值

c++ - 使用 SFML 资源管理器的 C++ 模板

c++ - 将模板化智能指针类型作为模板参数传递

c++ - CRTP 和基类定义的类型的可见性

C++ 函数对象无法使用 std::for_each 创建 sum (VS2012)

c++ - 将结构传递给函数并在其中输入数据

c++ - 为什么 SFINAE 只适用于这两个看似相同的函数之一?

python - Django URL、模板、模型和 View 的命名约定