Search code examples
c++templatespointersgeneric-collections

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


Say I had a template like template<typename T> class my_data_structure. I would like the template to be able to handle the primitive types e.g. int and objects, as well as pointer variable (e.g. Vertex*).

The operations can be:

  1. Direct comparisons on integers or objects e.g. using >,
  2. object->compare(another_object) for pointer variables.

Can this be done without having to write two different data structures? I'm sorry I cannot post more code, but this is part of a school project, and I would rather not be accused of plagiarism.


Solution

  • Use a partial template specialization:

    Primary template:

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

    Partial template specialization for T*

    template<class T>
    struct Foo<T*>
    {
        bool operator ==( const T &otherObj )
        {
            return m_obj->compare( otherObj );
        }
        T* m_obj;
    };