M
Markus Dehmann
I defined a base class in order to put heterogeneous values into a
standard container: All values that I store in the container are
derived from my base class.
Now when I iterate over the elements of the container and want my
original values back - can I avoid excessive casting and if
statements? (see my sample code below.) Can I make it more elegant?
#include <iostream>
#include <vector>
using namespace std;
class Value{
public:
virtual ~Value(){}
};
template< typename T >
class SpecVal: public Value{
private:
T m_t;
public:
SpecVal (T const& t = T()): m_t(t) {}
T &getValue() {return m_t;}
};
void processString(const string &s){
cout << "String: " << s << endl;
}
void processFloat(const float &f){
cout << "Float: " << f << endl;
}
int main(){
vector<Value *> v;
v.push_back(new SpecVal<float>(3.5));
v.push_back(new SpecVal<string>("test"));
for(vector<Value *>::iterator i = v.begin(); i != v.end(); ++i){
if(SpecVal<float>* f = dynamic_cast<SpecVal<float>*>(*i)){
processFloat(f->getValue());
}else if(SpecVal<string>* s = dynamic_cast<SpecVal<string>*>(*i)){
processString(s->getValue());
}
delete *i;
}
}
standard container: All values that I store in the container are
derived from my base class.
Now when I iterate over the elements of the container and want my
original values back - can I avoid excessive casting and if
statements? (see my sample code below.) Can I make it more elegant?
#include <iostream>
#include <vector>
using namespace std;
class Value{
public:
virtual ~Value(){}
};
template< typename T >
class SpecVal: public Value{
private:
T m_t;
public:
SpecVal (T const& t = T()): m_t(t) {}
T &getValue() {return m_t;}
};
void processString(const string &s){
cout << "String: " << s << endl;
}
void processFloat(const float &f){
cout << "Float: " << f << endl;
}
int main(){
vector<Value *> v;
v.push_back(new SpecVal<float>(3.5));
v.push_back(new SpecVal<string>("test"));
for(vector<Value *>::iterator i = v.begin(); i != v.end(); ++i){
if(SpecVal<float>* f = dynamic_cast<SpecVal<float>*>(*i)){
processFloat(f->getValue());
}else if(SpecVal<string>* s = dynamic_cast<SpecVal<string>*>(*i)){
processString(s->getValue());
}
delete *i;
}
}