jvm
jvm

Reputation: 369

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 vectors 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).

Upvotes: 2

Views: 613

Answers (1)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133122

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

Upvotes: 4

Related Questions