在 C++ 中创建模板以处理指向对象和基本类型的指针

Creating templates in C++ to handle pointers to objects and primitive types

假设我有一个像 template<typename T> class my_data_structure 这样的模板。我希望模板能够处理原始类型,例如int 和对象,以及指针变量(例如 Vertex*)。

操作可以是:

  1. 直接比较整数或对象,例如使用 >
  2. object->compare(another_object) 用于指针变量。

这可以不用写两个不同的数据结构来完成吗?抱歉,我不能 post 更多代码,但这是学校项目的一部分,我不想被指责为剽窃。

使用 partial template specialization:

主模板:

template<typename T>
struct  Foo
{
    bool operator ==( T otherData )
    {
        return m_data == otherData;
    }
    T m_data;
};

T*

的部分模板专业化
template<class T>
struct Foo<T*>
{
    bool operator ==( const T &otherObj )
    {
        return m_obj->compare( otherObj );
    }
    T* m_obj;
};

您需要进行部分特化以处理指针和非指针类型。要处理所有整数类型,您可以使用 std::enable_ifstd::is_arithmetic

//non pointer type definition
template<typename T> class my_data_structure 
{

  bool operator(std::enable_if<not std::is_arithmetic<T>::value> other)
  {
    // do your bidding here for non arithmetic objects
  }

  bool operator(std::enable_if<std::is_arithmetic<T>::value> other)
  {
    // do your bidding here for ints/floats etc
  }
};

//pointer type specilization ( call object->compare(another_object) as needed

template<typename T> class my_data_structure<T*> 
{
   //... put the actual comparator here
};