This is a slightly different question for this ([ Access to a method from a template derived class without using virtual functions in C ++? ), Which I recently asked.
I would like to instantiate an object using the factory template method, and then we can only set and get the value based on the original type provided to this element.
Here is a brief example of what I'm trying to achieve:
boost::shared_ptr<Item> item = Item::create<float>();
item->setValue(5);
float value = item->value();
In fact, the only time setValue fails is the lack of an implicit conversion from what was set to the initial "type" of the internal value in Item.
So, if I made the entire Item class a template that accepts a type, I would need to specify the type of the value each time I created a generic pointer to an Item that is really uninteresting to me.
The next approach I took was to try to save the initial type in the class and use boost :: any for internal storage, casting the internal type to the first type specified if there was an implicit conversion. However, I slowed down to store and compare type information, initially looking at std :: type_info, but since setValue took boost :: any, there was no way to compare what was actually passed.
(A small extension for this may provide a variant option in the template argument when creating and returning a value in the original given type.)
, - , , , , - , ?