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
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.