用C++创建模板来处理指向对象和基元类型的指针

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

本文关键字:对象 类型 指针 创建 C++ 建模 处理      更新时间:2023-10-16

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

操作可以是:

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

这可以在不必编写两种不同的数据结构的情况下完成吗?很抱歉我不能发布更多的代码,但这是学校项目的一部分,我宁愿不被指责抄袭。

您需要进行部分专门化来处理指针和非指针类型。要处理所有的积分类型,可以使用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
};

使用部分模板专用化:

主要模板:

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