I need a container/wrapper C++ class which holds a single, arbitrary value. Once this value is set only values of the same type should be accepted.
This is the code I’ve been experimenting with.
struct Genome {
struct FitnessConcept {};
template<typename T>
struct Fitness : public FitnessConcept{
T value;
Fitness(T value) : value(value){}
};
std::shared_ptr<FitnessConcept> fitness;
template<typename T>
void setFitness(T value) {
fitness.reset(new Fitness<T>(value));
}
template<typename T>
T getFitness() {
return static_cast<Fitness<T>*>(fitness.get())->value;
}
};
While Genome can hold arbitrary values, it does not restrict the type once the first is set, i.e. the following code is valid:
Genome g;
g.setFitness(0.2);
g.setFitness("foo"); //this should fail
UPDATE
Both compile and runtime failures are ok.
Apart from using libraries like
Boost.Any, a small modification of your source already works. Simply add a templated constructor to initialize theGenome, and have an equality test using the (implementation defined)typeid()operator between the new and old types.Output on Ideone. There are several variations possible. E.g. if you do a
dynamic_cast< u->get() >(fitness_->get())then this will throw astd::bad_castexception if the current underlying type ofGenomeis not convertible to the new type. This would allow you to changeGenometo derived type but not to completely unrelated types.