Reputation: 2271
Can someone please help me to understand why this code compiles:
class A {};
class B : public A {};
void foo( A ) {}
int main() {
B b;
foo( b );
}
but this not:
class A {};
class B : public A {};
template< typename T >
class wrapper {};
void foo( wrapper<A> ) {}
int main() {
wrapper<B> b;
foo( b );
}
The only difference in the second code (i.e., the code that does not compile) is that the classes A
and B
are wrapped as template parameters in the class wrapper
; the wrapping, surprisingly, seems to hinder the conversion from B
to A
.
It would also be great if someone can help me to fix the second code.
Upvotes: 0
Views: 52
Reputation: 6395
class B
is derived from class A
, so each B
is an A
and can be used in its place. However, wrapper<A>
has no relationship with wrapper<B>
- why would it?
Consider this example: if B is the son of A, would B’s wife be the son of A’s wife (obviously not - they have no relation).
To accomplish such a relation, you would need to derive wrapper<B>
from wrapper<A>
, which is not possible with wrapper<>
being a template class. Consider other approaches, where you send B
into the methods of the wrapper<A>
class or similar (works, as it is a A
).
Upvotes: 2