【问题标题】:Creating templates in C++ to handle pointers to objects and primitive types在 C++ 中创建模板以处理指向对象和原始类型的指针
【发布时间】:2015-12-05 17:00:30
【问题描述】:

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

操作可以是:

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

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

【问题讨论】:

  • 您可以添加一个额外的模板参数,告诉它如何比较它?使用自定义比较器查看 std::map
  • @NeilKirk,我正在考虑做类似的事情,传递一个静态函数,但我也会看看这个。
  • @Gernot1976 我没有意识到你可以做到这一点!决赛结束后,我一定会试试这个。

标签: c++ templates pointers generic-collections


【解决方案1】:

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

【讨论】:

  • 编译器足够聪明,我不需要专门化 int 吗?或者我是否必须为 int、long、double 等编写专业化...
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2016-07-25
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 2020-10-20
    • 2011-05-04
    • 1970-01-01
    相关资源
    最近更新 更多