访问类中的值类似于boost :: any [英] Accessing Values in a Class Similar to boost::any
问题描述
我为教育目的做一个简单的 boost :: any
类的类,但我不知道如何访问存储的值。我可以完美地设置值,但是当我尝试访问holder类中的任何成员时,编译器只是抱怨该成员在其派生类中找不到。我不能将成员声明为 virtual
因为模板。
I'm making a simple boost::any
-like class for educational purposes, but I can't figure out how to access the stored value. I can set the value perfectly, but when I try to access any member in the "holder" class the compiler just complains that the member wasn't found in the class it was derived from. I can't declare the members as virtual
because of the templates.
这里是相关的代码:
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的魔力。
It's fine to add virtual functions to templates- just the functions themselves cannot be templates. A templated class or struct can still have virtual functions just fine. You need to use the magic of 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
而不是throwing。您还没有处理过 StoredValue
的先前值的记忆,但我将其留给您。
If you change Get to return a Datatype*
you can return NULL
instead of throwing. You also haven't handled the memory of the previous value of StoredValue
, but I'm leaving that up to you.
这篇关于访问类中的值类似于boost :: any的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!