Context
I would like to create a vector of Attribute variables, T marking any other class. A sample:
template<typename T>
class Attribute{
public:
string name;
T value;
Attribute(){ }
Attribute(string n, T val){ name = n; value = val; }
string getName(){ return name; }
string setName(string n){ name = n; }
T getAttr(){ return value; }
void setAttr(T v){ value = v; }
};
Now, from this I would like to create a vector, which can hold different kind of Attributes, like Attribute\ and Attribute\. Since you have to give to the template used for Attribute when creating the vector, I figured to use an abstract base class, or Interface.
The real problem
I have an interface, called AttributeInterface, which defines the possible methods for an Attribute, but I cannot define the getter and setter methods for the Attribute.value variable, as I don't know their signature before using the template. If I use a template with AttributeInterface, then I'm back at the problem mentioned on the previous block.
class AttributeInterface{
public:
virtual string getName();
virtual string setName();
virtual ?? getAttr();
virtual void setAttr(?? v);
};
template<typename T>
class Attribute: public AttributeInterface{
public:
string name;
T value;
Attribute(){ }
Attribute(string name, T val){ this.name = name; value = val; }
string getName(){ return name; }
string setName(string n){ name = n; }
T getAttr(){ return value; }
void setAttr(T v){ value = v; }
};
And this would be the expected usage:
std::vector <??> vec;
// Or something along the lines of std::vector<AttributeInterface*> vec;
vec.push_back(new Attribute<float>("a", 1.0));
vec.push_back(new Attribute<int>("a", 10));
For reference, in a dynamically typed language like Python, the use case would be simply
class Attribute:
...
def get(self):
return self.value
def set(self,v):
self.value = v
l = []
l.append(Attribute('a',1.5))
l.append(Attribute('a',"foo"))
for i in l:
print(i.get())
Is my original idea even feasible in c++? Or is there any easier/better method to reach the behavior described with the Python example?
Thanks in advance.