C ++ - 如何检查(在运行时)模板函数类型是否与函数参数匹配

时间:2016-12-06 17:17:31

标签: c++ templates polymorphism

template <class T> 
class Links {
private:
  std::vector<Base*> linkVec;

public:
  Links<T>& operator += (Base*);
};

template <class T>
Links<T>& Links<T>::operator+=(Base* b) {

  //base is abstract, b will be passed in as derived type of b
  //I want to ONLY add base pointers to the SAME derived type to linkVec
  //How can I check at run-time (using down cast or dynamic cast?) if the 
  //derived type being passed is the same as the other derived types in the linkVec?
  //I would like to throw an exception if a different derived type is attempted to be added 
  //to linkVec

  linkVec.push_back(b);

  return *this;
}

评论应该总结一下我在这里要做的很好。但简而言之,我有一个模板类,其中一个向量仅包含相同派生类型的指针。如果添加了不同派生类型的指针,我想抛出异常。我不确定如何在运行时检查类型,并希望有任何见解。

0 个答案:

没有答案