Home > other >  Im studying polymorphism and ran into a problem
Im studying polymorphism and ran into a problem

Time:02-03

I created an abstract base class with two sub classes:

class Base {
public: 
    int a, b, c;
    virtual void unreal() = 0; 
};

class Sub1: public Base {
public:
    virtual void unreal() {}
};

class Sub2: public Base {
public:
    virtual void unreal() {}
};

I want to create a function that I can pass parameter of both types:

vector<Sub1> v1 and vector<Sub2> v2 

into it, using something like:

Function(vector<Base&> v) {}

But it didn't work. So I want to know is there anyway to do it?

CodePudding user response:

With C 20 you can achieve that with the following:

template<std::derived_from<Base> T>
void function(const std::vector<T>& v) {}

The above is using templates to accommodate any type of vector (by allowing the function to accept const std::vector<T>& where T is a template parameter). But to restrict T to be only derived of Base we add inside the template the restriction on T, requiring it to be std::derived_from<Base>.

Code: http://coliru.stacked-crooked.com/a/8aaa0c941fdc493e


Before C 20 it would require some more cumbersome SFINAE:

template<typename T, std::enable_if_t<std::is_base_of_v<Base, T>>* Dummy = nullptr>
void function(const std::vector<T>& v) {}

Code: http://coliru.stacked-crooked.com/a/0b7d98a84b6139b7

CodePudding user response:

Yes, you can pass both vector<Sub1> and vector<Sub2> into a function by using a reference to vector<Base>:

void Function(vector<Base>& v) {}

This should work because Sub1 and Sub2 are derived classes from Base, and a reference to a derived class can be passed to a reference to its base class. However, the function will not be able to modify the objects in the vector as the objects are passed by reference to a const vector.

  • Related