C++模板协方差

Twi*_*ter 5 c++ polymorphism templates covariance

你能在C++中使用协方差适用于泛型类型(通过模板)吗?

我已经发现这个问题回答了我的问题,但我再次问它,因为它已经有两年了!虽然有人解释说模板中的C++中没有协方差,但没有解释!

你能帮我讲解这个话题的新闻/解释吗?

Che*_*Alf 5

考虑到之前的问题作为澄清手段,您似乎在问“为什么T<Derived>通常不源自 ” T<Base>

考虑T= std::shared_ptr

您不希望能够执行以下操作:

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
}
Run Code Online (Sandbox Code Playgroud)