【发布时间】:2016-07-29 11:26:38
【问题描述】:
假设我有类层次结构。 一种; B1、B2、B3-Bn 都派生自 A,还有一些 C 类派生自不同的 B。 我想要一个类“UnifiedStorage”来存储A派生类,它不应该被模板化,但它本身应该有std::shared_ptr并且有两个功能:
template <typename T>
setData(std::shared_ptr<T> data/* A's derived class */)
template <typename T>
std::weak_ptr<T> getData()
我发现唯一可能的实现是像 Keeper 一样创建 smth:
class UnifiedStorage{
class Keeper {
public:
virtual ~Keeper (){
}
};
template <typename DataType>
class SpecificKeeper : public Keeper {
public:
SpecificKeeper (std::shared_ptr<DataType> data): data(data) {}
~SpecificKeeper() = default;
std::shared_ptr<DataType> data;
};
template <typename SpecificDataType>
void setData (std::shared_ptr <SpecificDataType> d) {
keeper.reset( new SpecificKeeper <SpecificDataType> (d) );
}
template <typename RequestedDataType>
std::shared_ptr <RequestedDataType> getData () {
SpecificKeeper <RequestedDataType>* specificKeeper = dynamic_cast <SpecificKeeper <RequestedDataType> * > (keeper.data());
if (specificKeeper == nullptr){
return std::shared_ptr <RequestedDataType> ();
}else{
return specificKeeper->data;
}
}
private:
std::unique_ptr<Keeper> keeper;
}
但这种认识有很强的负面影响。我只能让 shared_ptr 输入我在 setData 中设置的类型。
例如,如果我调用了 setData<B>(std::shared_ptr<B>) 我不能 getData<A> 它返回 null,但如果我调用 setData<A>(std::shared_ptr<B>) getData<A> 将返回正确的指针。
【问题讨论】:
-
你不能用:
void setData(std::shared_ptr<A> ptr) { m_data = ptr; } template <typename T> std::weak_ptr<T> getData() { return std::static_pointer_cast<T>(m_data); },成为会员std::shared_ptr<A> m_data;吗? -
我有一个邪恶的:拥有
std::function<void()>并存储{ throw *this }。不用于实际代码,仅用于完整性和下一个 IOCCC。