C++ class with template member variable

前端 未结 2 1109
迷失自我
迷失自我 2020-11-30 20:33

I am trying to solve a programming problem that consists of an object (call it Diagram), that contains several parameters. Each parameter (the Parameter class) can be one of

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 21:14

    You got very close. I added a few bits because they're handy

    class ParameterBase
    {
    public:
        virtual ~ParameterBase() {}
        template const T& get() const; //to be implimented after Parameter
        template void setValue(const U& rhs); //to be implimented after Parameter
    };
    
    template 
    class Parameter : public ParameterBase
    {
    public:
        Parameter(const T& rhs) :value(rhs) {}
        const T& get() const {return value;}
        void setValue(const T& rhs) {value=rhs;}    
    private:
        T value;
    };
    
    //Here's the trick: dynamic_cast rather than virtual
    template const T& ParameterBase::get() const
    { return dynamic_cast&>(*this).get(); }
    template void ParameterBase::setValue(const U& rhs)
    { return dynamic_cast&>(*this).setValue(rhs); }
    
    class Diagram
    {
    public:
        std::vector v;
        int type;
    };
    

    Diagram can then do stuff like these:

    Parameter p1("Hello");
    v.push_back(&p1);
    std::cout << v[0]->get(); //read the string
    v[0]->set("BANANA"); //set the string to something else
    v[0]->get(); //throws a std::bad_cast exception
    

    It looks like your intent is to store resource-owning pointers in the vector. If so, be careful to make Diagram have the correct destructor, and make it non-copy-constructable, and non-copy-assignable.

提交回复
热议问题