Let's have the following simple function (the body of my function is more complicated but for the sake of simplicity):
unsigned VctSize(const vector< Base_class > vct) {
return vct.size()
}
How can I make the function accept vectors of derived classes of Base_class on input? And can I make the function accept vect开发者_运维问答ors of any type?
In other words, I would like to a write a single function that takes vector of any derived class of Base_class and uses only vector manipulation (no members or member functions of the derived classes).
This will accept vectors of any type
template <class T>
unsigned VecSize(const vector<T>& vct)
{
return vct.size();
}
In order to accept only vectors of derived classes, you can use boost::enable_if
template<class T>
typename enable_if<is_base_and_derived<BaseClass, T>, unsigned>::type
VecSize(const vector<T>& vct)
{
return vct.size();
}
精彩评论