c++ - 模板类函数 T : How to find out if T is a pointer?

标签 c++ templates typetraits

作为 this question 的后续行动: 我需要在这样的类函数中做出决定:

template< typename T > bool Class::Fun <T*> ( T& variable ) {...}

T是否为指针

在上面引用的问题中,答案是使用部分模板特化。据我所知,这对于类函数是不可能的。这是真的?如果是这样,是否有另一种方法可以确定 T 是否为指针?

最佳答案

无需特化成员函数。在该答案中使用了独立结构。您仍然可以在类成员函数中自由使用它。

// stand-alone helper struct
template<typename T>
struct is_pointer { static const bool value = false; };    
template<typename T>
struct is_pointer<T*> { static const bool value = true; };

// your class
class Class{
public:
 template<typename T>
 void Fun(T& variable) {
     std::cout << "is it a pointer? " << is_pointer<T>::value << std::endl;
 }
};

另一方面,您可以重载函数:

class Class {
public:
 template<typename T>
 void Fun(T& variable) {
     std::cout << "is it not a pointer! " << std::endl;
 }
 template<typename T>
 void Fun(T*& variable) {
     std::cout << "is it a pointer! " << std::endl;
 }
};

关于c++ - 模板类函数 T : How to find out if T is a pointer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1412737/

相关文章:

c++ - 为什么结构内的命名 union 会覆盖其他结构成员?

python - 在C++中模拟python的 "in"

c++ - 为参数顺序不同的模板类创建比较特征

c++ - 如何发出昂贵与廉价模板参数的信号?

c++ - unordered_map 结构化绑定(bind)中的推导类型

c++ - 显示深度优先搜索图遍历 C++

c++ - QTreeWidget垂直滚动条跳得太远

C++如何使用相同的函数两次使用不同的名称和变量的不同名称

c++ - 使用模板读取 vector

c++ - boost::is_enum 它是如何工作的?