Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Template Covariance [duplicate]

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?

like image 348
TwistAndShutter Avatar asked Sep 29 '22 23:09

TwistAndShutter


1 Answers

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
}
like image 69
Cheers and hth. - Alf Avatar answered Oct 03 '22 00:10

Cheers and hth. - Alf