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

Max*_*xpm 3 c++ oop derived-class 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."
    }
};
Run Code Online (Sandbox Code Playgroud)

Pup*_*ppy 5

将虚拟函数添加到模板中是很好的 - 只是函数本身不能是模板.模板化的类或结构仍然可以很好地具有虚函数.你需要使用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."
    }
};
Run Code Online (Sandbox Code Playgroud)

如果你改变Get来返回a Datatype*你可以返回NULL而不是扔.你还没有处理以前的值的记忆StoredValue,但我要把它留给你.