In your case you don't need the base class. And in this case you need to use
map<string, _Property<int>> propertiesInt;
map<string, _Property<string>> propertiesString;
update:
I changed my map definition and assignments to:
1 2
map<string, Property*> properties;
properties["path"] = new _Property<string>("/var/log/blabla");
and I removed the virtual getValue method from the base class, putting
a virtual destructor instead for polymorphism.
my code works, but in order to retrieve a property value i need to do:
In your case you don't need the base class. And in this case you need to use
map<string, _Property<int>> propertiesInt;
map<string, _Property<string>> propertiesString;
I want to make it modular so I can quickly add vector properties, or any other class. I don't want to limit myself to string or int.
template in C++ is compile time feature and so you MUST point type of template in the moment of object instantination.
So it's need to use the follwoing
map<string, _Property<int>> propertiesInt;
map<string, _Property<string>> propertiesString;
Of course, you can specify other types, not only string or int, it can be your own type
template in C++ is compile time feature and so you MUST point type of template in the moment of object instantination.
So it's need to use the follwoing
map<string, _Property<int>> propertiesInt;
map<string, _Property<string>> propertiesString;
But that's the whole beauty of polymorphism...
suppose my classes looked like that:
1 2 3 4 5 6 7 8 9 10 11 12
class BaseProperty{
public:
virtualint getSize(void) const {return 0;}
};
template< class T >
class Property: public BaseProperty{
T element;
public:
int getSize(void) const {returnsizeof(element);}
};
I could use them like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class myBigObj{
char arr[500];
};
int main()
{
map<string, BaseProperty*> properties;
properties["a"] = new Property<int>();
properties["b"] = new Property< map<string,int> >();
properties["c"] = new Property<myBigObj>();
cout << properties["a"]->getSize() << endl;
cout << properties["b"]->getSize() << endl;
cout << properties["c"]->getSize() << endl;
delete properties["a"];
delete properties["b"];
delete properties["c"];
return 0;
}
and the ouput would be:
4
24
500
what I want is basically the same, only the return type of getSize is changed according to the template, and Im asking what it's return type should be in the baseClass.
If you know all the value types at compile time (and there aren't that many), you could
use boost::variant. Otherwise, you could look at using boost::any. Failing that, you
could research type erasure and use that.