问题
First something that should work, then something that doesn't. Why doesn't it is the question.
I declare two classes:
class Base { ... };
class Derived : public Base { ... };
I then have the following function elsewhere:
void foo(shared_ptr<Base> base);
The following code should work right?
share_ptr<Derived> derived;
foo(derived);
Now, forget the above, I declare three classes:
class Foo { ... };
template <typename TYPE> class Base { ... };
class Derived : public Base<Foo> { ... };
Elsewhere, I declare a templated function:
template <typename TYPE> void foo(shared_ptr<Base<TYPE> > base);
The following code does not work:
shared_ptr<Derived> derived;
foo(derived);
It says that there is no matching function foo(...) found which accepts share_ptr<Derived>
First, should the original example work? And second, what do you think could be the issue in the second example where I have a shared_ptr
to a class that is derived from a specialized base class.
回答1:
I don't think the compiler will go through a level of indirection in that way. Rather, you can explicitly instantiate foo with TYPE set to Foo. Eg, the following compiles via g++:
#include<boost/shared_ptr.hpp>
class Foo {};
template <typename T> class Base {};
class Derived : public Base<Foo> {};
template<typename T>
int foo(boost::shared_ptr<Base<T> > base) {return 0;}
boost::shared_ptr<Derived> derived;
int t = foo<Foo>(derived);
int main() {return 0;}
回答2:
This might be a copy and paste error, but just to cover all the bases, you missed the 'd' in 'shared' for share_ptr<Derived>
.
来源:https://stackoverflow.com/questions/5385355/c-passing-a-derived-class-shared-ptr-to-a-templated-function