访问类中的值类似于boost :: any

我正在为教育目的制作一个简单的
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
而不是扔。你还没有处理previous6ѭ之前值的记忆,但是我要把它留给你了。     
你需要先把它投到
ValueStorage
。 还要将虚拟析构函数添加到ValueStorageBase类,以获得多态类。没有它你不能运行时检查你的铸件是否正常:)。 之后你可以写:
template <typename Datatype>
    Datatype Element_cast()
    {
        //throw exception for a wrong cast
        if(typeid(*StoredValue)!=typeid(ValueStorage<Datatype>) )
               throw exception;

        //we already checked, that our type casting is OK,
        //So no need for dynamic_cast anymore
        return static_cast<ValueStorage*> (StoredValue)->value;
    }
    

要回复问题请先登录注册