6

Can you use the covariance propriety for the generic types (through the templates) in C++?

I already found this question that answers my question, but I ask it again since it has already been two years! In addiction, though it is explained that there can be no covariance in C++ in templates, there is no explanation about that!

Can you help me about news/explanation of this topic?

Community
  • 1
  • 1
TwistAndShutter
  • 239
  • 2
  • 15

1 Answers1

5

Given the reference to an earlier question as a clarification device, it seems you are asking why T<Derived> is not usually derived from T<Base>.

Consider T = std::shared_ptr.

You don't want to be able to do this:

void foo( shared_ptr<Base>& p ) { p.reset( new Derived2 ); }

auto main() -> int
{
    shared_ptr<Derived1> p;
    foo( p );   // Oops, p now points to unrelated Derived2
}
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331