【发布时间】:2017-02-26 15:49:13
【问题描述】:
我已将 Child 对象的共享指针存储在 Base 共享指针的向量 中,我需要将 Base 向量的元素动态转换为其 Child类型,这样我就可以使用儿童特定签名调用函数。
下面是一个例子。第一个代码块定义了类层次结构和我想使用的“识别”函数。第二个代码块给出了一个具体示例,说明我想如何调用特定于 TYPE 的“识别”函数,因为我可以将原始对象类型从 Base 类转换为 Child 类(例如 A ,B,C)。
有什么模式或技术可以解决这个问题吗?
#include <iostream>
#include <memory>
#include <vector>
class Base {};
class A : public Base{};
class B : public Base{};
class C : public Base{};
class CollectionOfBase
{
public:
void add (std::shared_ptr<Base> item){m_items.push_back(item);}
std::vector<std::shared_ptr<Base>> const& getItems() const {return m_items;}
private:
std::vector<std::shared_ptr<Base>> m_items;
};
// I want to use these 3 functions instead of identify( std::shared_ptr<Base> const& )
void identify( std::shared_ptr<A> const& )
{
std::cout << "A" << std::endl;
}
void identify( std::shared_ptr<B> const& )
{
std::cout << "B" << std::endl;
}
void identify( std::shared_ptr<C> const& )
{
std::cout << "C" << std::endl;
}
//This function works in the below for loop, but this is not what I need to use
void identify( std::shared_ptr<Base> const& )
{
std::cout << "Base" << std::endl;
}
下面,你可以找到第二个代码块:
int main()
{
using namespace std;
CollectionOfBase collection;
collection.add(make_shared<A>());
collection.add(make_shared<A>());
collection.add(make_shared<C>());
collection.add(make_shared<B>());
for (auto const& x : collection.getItems())
{
// THE QUESTION:
// How to distinguish different type of items
// to invoke "identify" with object specific signatures (e.g. A,B,C) ???
// Can I cast somehow the object types that I push_back on my Collection ???
// Note that this loop does not know the add order AACB that we pushed the Child pointers.
identify(x);
}
/*
The desired output of this loop should be:
A
A
C
B
*/
return 0;
}
代码也可以在Ideone上找到。
【问题讨论】:
标签: c++ dynamic polymorphism c++14 dispatch