我如何使用std :: shared_ptr实现多态? [英] How do I implement polymorphism with std::shared_ptr?
问题描述
我已经看到关于此主题的其他一些问题,但仍未找到答案 - 我想我错过了一些东西:
我定义了两个简单的测试类:
I defined two simple test classes:
class TestBase
{
public:
TestBase ( ) { };
~ TestBase ( ) { };
protected:
inline virtual int getInt ( )
{
return 0;
}
};
class TestDerived : public TestBase
{
protected:
inline int getInt ( ) override
{
return 1;
}
};
我使用 std :: shared_ptr声明typedefs以简化它们的使用:
typedef std::shared_ptr<TestBase> spBase;
typedef std::shared_ptr<TestDerived> spDerived;
问题:我无法编译代码来使用这些 shared_ptr $ c $即使
base
在所有这些情况下实际上都是 spDerived
的实例:
Problem: I cannot compile code to use these shared_ptr
declarations polymorphically, even though base
in all these cases is actually an instance of spDerived
:
spBase base;
spDerived derived = static_cast < spDerived > ( base );
错误:没有匹配函数调用'std :: shared_ptr :: shared_ptr(spBase&)
error: no matching function for call to ‘std::shared_ptr::shared_ptr(spBase&)
spDerived derived = dynamic_cast < spDerived > ( base );
error:can not dynamic_cast'base'(type'spBase {aka class std :: shared_ptr}'(target不是指针或引用)
error: cannot dynamic_cast ‘base’ (of type ‘spBase {aka class std::shared_ptr}’) to type ‘spDerived {aka class std::shared_ptr}’ (target is not pointer or reference)
spDerived derived = static_pointer_cast < spDerived > ( base );
错误:从'std :: shared_ptr'转换为非标量键入
'spDerived {aka std :: shared_ptr}'请求
$ b
error: conversion from ‘std::shared_ptr >’ to non-scalar type ‘spDerived {aka std::shared_ptr}’ requested
spDerived derived = dynamic_pointer_cast < spDerived > ( base );
错误:从'std :: shared_ptr'转换为非标量键入
'spDerived {aka std :: shared_ptr}'请求
error: conversion from ‘std::shared_ptr >’ to non-scalar type ‘spDerived {aka std::shared_ptr}’ requested
在默认的GCC工具链的Ubuntu 14.04盒子上使用C ++ 11。编译器是gcc-4.9。
我做错了什么?不能使用多态的shared_pointer?
I'm using C++11 on an Ubuntu 14.04 box with the default GCC tool chain. Compiler is gcc-4.9. What am I doing wrong? Can't a shared_pointer be used polymorphically?
推荐答案
传入 std :: static_pointer_cast
和 std :: dynamic_pointer_cast
作为第一个类型模板参数是转换的指针类型本身的类型,而不是 smart 指针类型:
static_pointer_cast<T>(arg);
.~~~^
v
template <class T, class U>
.~~~~^
v
shared_ptr<T> static_pointer_cast(const shared_ptr<U>& r);
dynamic_pointer_cast<T>(arg);
.~~~~^
v
template <class T, class U>
.~~~~^
v
shared_ptr<T> dynamic_pointer_cast(const shared_ptr<U>& r);
有了这个说法,你可以这样称呼它:
With that said, you could call it like below:
spBase base = std::make_shared<TestDerived>();
spDerived derived = std::dynamic_pointer_cast<spDerived::element_type>(base);
// or:
spDerived derived2 = std::dynamic_pointer_cast<TestDerived>(base);
这篇关于我如何使用std :: shared_ptr实现多态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!