C ++ pattern covariance

Can you use the correct covariance for generic types (via templates) in C ++?

I have already found this question that answers my question, but I ask it again, since two years have already passed! Depending, although it is explained that the templates cannot have covariance in C ++, there is no explanation for this!

Can you help me with the news / explanations of this topic?

+5
source share
1 answer

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

Consider T = std::shared_ptr .

You do not want this to be possible:

 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 } 
+4
source

Source: https://habr.com/ru/post/1201761/


All Articles