C++ passing a derived class shared_ptr to a templated function

人走茶凉 提交于 2019-12-31 03:20:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!