我正在做一个简单的boost::any
-类似用于教育目的的课程,但我不知道如何访问存储的值。我可以完美地设置该值,但是当我尝试访问“holder”类中的任何成员时,编译器只是抱怨在它派生的类中找不到该成员。我无法将成员声明为virtual
因为模板。
这是相关代码:
class Element
{
struct ValueStorageBase
{
};
template <typename Datatype>
struct ValueStorage: public ValueStorageBase
{
Datatype Value;
ValueStorage(Datatype InitialValue)
{
Value = InitialValue;
}
};
ValueStorageBase* StoredValue;
public:
template <typename Datatype>
Element(Datatype InitialValue)
{
StoredValue = new ValueStorage<Datatype>(InitialValue);
}
template <typename Datatype>
Datatype Get()
{
return StoredValue->Value; // Error: "struct Element::ValueStorageBase" has no member named "Value."
}
};
将虚拟函数添加到模板中很好 - 只是函数本身不能是模板。模板化的类或结构仍然可以有虚函数。你需要使用dynamic_cast的魔力。
class Element
{
struct ValueStorageBase
{
virtual ~ValueStorageBase() {}
};
template <typename Datatype>
struct ValueStorage: public ValueStorageBase
{
Datatype Value;
ValueStorage(Datatype InitialValue)
{
Value = InitialValue;
}
};
ValueStorageBase* StoredValue;
public:
template <typename Datatype>
Element(Datatype InitialValue)
{
StoredValue = new ValueStorage<Datatype>(InitialValue);
}
template <typename Datatype>
Datatype Get()
{
if(ValueStorage<DataType>* ptr = dynamic_cast<ValueStorage<DataType>*>(StoredValue)) {
return ptr->Value;
else
throw std::runtime_error("Incorrect type!"); // Error: "struct Element::ValueStorageBase" has no member named "Value."
}
};
如果你改变 Get 返回一个Datatype*
你可以返回NULL
而不是扔。你也没有处理过之前值的内存StoredValue
,但我将其留给你。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)