C ++通过一个派生类shared_ptr的一个模板函数 [英] C++ passing a derived class shared_ptr to a templated function
问题描述
首先东西应该工作,那么一些不。为什么它是不是这个问题。
First something that should work, then something that doesn't. Why doesn't it is the question.
我声明了两个类:
class Base { ... };
class Derived : public Base { ... };
然后我有以下的其他功能:
I then have the following function elsewhere:
void foo(shared_ptr<Base> base);
以下code应该工作吧?
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);
以下code不工作:
The following code does not work:
shared_ptr<Derived> derived;
foo(derived);
报告说,没有发现匹配函数foo(...),它接受 share_ptr&LT;衍生GT;
首先,应该在原来的例子工作?第二,你认为什么可能是在我有一个的shared_ptr
来是从一个专门的基类派生的类。
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.
推荐答案
我不认为编译器将通过间接的那样的水平。相反,你可以明确地实例化类型设置为富富。例如,通过G ++下面编译:
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;}
这篇关于C ++通过一个派生类shared_ptr的一个模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!