Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Quickly check whether C++ template instances have the same parameters

4.20/5 (5 votes)
5 Feb 2012CPOL 44.6K  
How to check whether two template instances of a C++ class have the same template parameters without using dynamic_cast

Imagine the following C++ class structure (code is reduced):


C++
class BaseClass {
public:
  virtual bool equals(BaseClass* other) = 0;
};

template<T>
class ChildClass {
public:
  virtual bool equals(BaseClass* other) {
    // How to check whether this cast is ok?
    ChildClass<T> otherCast = static_cast<ChildClass<T>>(other);
  }
};

How to check whether the static_cast is valid? One way is to use dynamic_cast.


Here's an alternative if you don't want/can't use dynamic_cast, implemented through classID():


C++
class BaseClass {
public:
  virtual bool equals(BaseClass* other) = 0;
  virtual int classID() const = 0;
};

template<class T>
class ChildClass {
public:
  virtual bool equals(BaseClass* other) {
    if (this->classID() != other->classID()) {
      return false;
    }
    ChildClass<T> otherCast = static_cast<ChildClass<T>>(other);
  }

  virtual int classID() const {
    static int id; 
    return (int)&id; // generates a custom "id"
  }
};

Each template instantiation of ChildClass will have another ID. So, for example, ChildClass<MyClass> will have another ID as ChildClass<MyOtherClass>. Using the same template parameter(s) will result in the same ID.


Note: Although I've tested this only with Visual C++ 2010, it seems logical that this will work with other compilers too. I haven't tested this across DLL boundaries.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)