sajas
sajas

Reputation: 1599

Best way to treat std::reference_wrapper<Derived> as std::reference_wrapper<Base>

I have two classes, say 'Base' and 'Derived', where Derived class inherits Base class.

Then a container of references to Derived class instances (std::vector< std::reference_wrapper< Derived > > myContainer ).

And finally, I have a function that takes std::vector< std::reference_wrapper< Base > > as argument.

If I pass the container(myContainer) to the function, it doesn't compile:

enter image description here

If I change my container to hold references to Base, everything works fine and since it is a reference_wrapper, I believe, I will still have the polymorphic behaviour that I need. But this feels unclean as I am sure that my container will not hold anything other than Derived instances.

At the same time, the function that takes in the vector is supposed to work on both Derived and Base classes.

Minimal code:

#include <vector>
#include <functional>

class Base
{ /*some virtual stuff*/ };

class Derived : public Base
{};

void Fun( std::vector< std::reference_wrapper< Base > > const & container )
{}

int main()
{
    std::vector< std::reference_wrapper< Derived > > myContainer;
    Fun( myContainer ); // Error: no viable conversion
    return 0;
}

Live code: https://godbolt.org/z/SX5Gag

What is the best way to ask the Function to treat the container of Derived references as a vector of Base references?

Upvotes: 5

Views: 1089

Answers (1)

Aconcagua
Aconcagua

Reputation: 25526

That's just not possible:

std::vector< std::reference_wrapper< Derived > > d;
std::vector< std::reference_wrapper< Base > >& b = d;

What could happen, if this was legal?

SomeOtherDerivedClass o;
b.push_back(o); // sure, b is vector of Base, so legal

But b actually just is a reference to d, so you just managed to place a different, illegal type into d.

So even if Base is a base class of Derived, the same doesn't apply for the corresponding containers, be it std::vector or any other one.

Upvotes: 4

Related Questions