开发者

C++: function with vector of any derived class on input

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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜