用C++创建模板来处理指向对象和基元类型的指针
Creating templates in C++ to handle pointers to objects and primitive types
假设我有一个类似template<typename T> class my_data_structure
的模板。我希望模板能够处理基元类型,例如int
和对象,以及指针变量(例如Vertex*
)。
操作可以是:
- 直接比较整数或对象,例如使用CCD_
- 指针变量的
object->compare(another_object)
这可以在不必编写两种不同的数据结构的情况下完成吗?很抱歉我不能发布更多的代码,但这是学校项目的一部分,我宁愿不被指责抄袭。
您需要进行部分专门化来处理指针和非指针类型。要处理所有的积分类型,可以使用std::enable_if
和std::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;
};
相关文章:
- 在 C++ 中将一个模板类型的对象类型转换为另一个模板类型
- 了解 Python 中的对象类型
- 具有纯虚函数和指针数组对象类型的父类的指针数组
- 调用的对象类型 'double' 不是 report() 函数的函数或函数指针
- 基准、值、值类型、对象和对象类型(C++)
- JNI 如何将 Java 对象数组传递给相同对象类型的 C++ 数组
- 在构造过程中更改的对象类型
- 如何构建程序以避免查询对象类型?
- 如何使用Dynamic_cast获得对象类型
- 什么更有效率?在重载函数中或通过在基类函数中检查对象类型来实现
- static_cast实际上不是对象类型的类型是未定义的行为吗?
- 为什么 std::variant 不能容纳数组对象类型,而联合可以?
- 为什么类型转换对象不会更改其地址?有关对象类型的信息存储在哪里?
- 类返回对象类型,但如何返回和检查 null
- 是否可以在辅助功能中概括对象类型
- 表达式必须在C 中具有指针对象类型
- 下标需要数组或指针类型表达式必须具有指针对象类型
- 当将对象传递给具有参数作为引用类型的函数以及当其类对象类型时,会得到不同的输出
- 如何在运行时指定对象类型
- 我可以获取在重载的新运算符中使用新运算符的对象类型吗?