开发者

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

开发者 https://www.devze.com 2023-03-25 08:01 出处:网络
Let\'s have the following simple function (the body of my function is more complicated butfor the sake of simplicity):

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

精彩评论

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