C++ 将派生类 shared_ptr 传递给模板函数

标签 c++ templates inheritance boost shared-ptr

首先是应该起作用的东西,然后是不起作用的东西。为什么不是这个问题。

我声明了两个类:

class Base { ... };
class Derived : public Base { ... };

然后我在其他地方有以下功能:

void foo(shared_ptr<Base> base);   

下面的代码应该正确吗?

share_ptr<Derived> derived;
foo(derived);

现在,忘记上面的内容,我声明了三个类:

class Foo { ... };
template <typename TYPE> class Base { ... };
class Derived : public Base<Foo> { ... };

在其他地方,我声明了一个模板函数:

template <typename TYPE> void foo(shared_ptr<Base<TYPE> > base); 

以下代码无效:

shared_ptr<Derived> derived;
foo(derived);

它表示没有找到接受 share_ptr<Derived> 的匹配函数 foo(...)

首先,原始示例应该有效吗?其次,您认为第二个示例中的问题可能是什么 shared_ptr到派生自专门基类的类。

最佳答案

我不认为编译器会以这种方式进行一定程度的间接寻址。相反,您可以将 TYPE 设置为 Foo 来显式实例化 foo。例如,以下通过 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 传递给模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5385355/

相关文章:

c++ - node-gyp 项目的增量构建

c++ - 在 C++ 中如何将自引用作为参数传递?

c++ - VC++ SFINAE 给出错误 C2070 : 'overloaded-function' : illegal sizeof operand

c++ - 使用模板模板参数和 enable_if 获得正确的重载选择

java - Animal a = new Horse() 和 Horse c = new Horse() 之间的区别

java - 在Java中如何使用接受其父类的单个函数处理所有子类

c++ - 将 ISO 8859-X 转换为 UNICODE 的方法

c++ - 如何使用 -std=c++11 : ‘auto_ptr’ is deprecated 解决 g++ 警告

c++ - 推导模板函数中的数组大小,传递值与传递引用的差值

C++ 多重继承、基类可见性和可怕的菱形。将祖先基类重新公开为公共(public)?