I’m not sure how to explain it because I don’t really know the correct terms, but here is an example:
template <typename T>
struct PointerWrapper {
T *ptr;
};
struct Base {};
struct Derived : public Base {};
void test(PointerWrapper<Base>) {}
int main() {
PointerWrapper<Derived> p;
test(p);
return 0;
}
Since “Derived” is derived from “Base” and the “PointerWrapper” struct only works with pointers to the type specified by the template, there is nothing wrong with this. But the compiler complains:
asdfg.cpp:15:11: error: could not convert ‘p’ from ‘PointerWrapper<Derived>’ to ‘PointerWrapper<Base>’
I even tried test(reinterpret_cast<PointerWrapper<Base>>(p)), but it says:
asdfg.cpp:15:51: error: invalid cast from type ‘PointerWrapper<Derived>’ to type ‘PointerWrapper<Base>’
So what should I do?
PointerWrapper<Base>andPointerWrapper<Derived>are utterly different types, despite the relationship betweenBaseandDerived.If you want to allow any
PointerWrapper<>to be passed in, do:If you want to allow only
PointerWrapper<T>instances whereTis derived fromBase, do:If you’re using C++03, replace
std::withboost::and get rid of::value.