Re: What's the best way? STL containers and template.
- From: "Igor Tandetnik" <itandetnik@xxxxxxxx>
- Date: Wed, 15 Mar 2006 08:42:35 -0500
"nick" <nick@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
news:546182C5-13CB-4CA1-B9FE-7C9E9F386934@xxxxxxxxxxxxx
class Base { ... }
template <class T> Derived { T value; ...}
Was it the intention that Derived actually derive from Base? Yours
doesn't.
vector<Base *> v;
v.push_back(new Derived<float>(1.2));
v.push_back(new Derived<int>(2));
v.push_back(new Derived<string>("abc"));
What's the best way to get the "value" of elements in the vector v?
1. Define
float getFloat() =0;
int getInt() = 0;
string getStr() = 0;
in Base and either (a) use template specialization in Derived to
define these functions or (b) just define these functions in Derived
by checking typeid(value)==typeid(xxx)
2. Using type cast
cast the element of v into Derived<float>*, Derived<string>*, etc....
Which one is best? 1a, 1b, or 2? Or any better way?
Since you appear to be happy with a finite number of supported types,
I'd probably just do a discriminated union:
class Value {
public:
enum Type {INT, FLOAT, STRING};
Type getType();
int getInt();
// ...
private:
Type type;
union {
int ival;
float fval;
}
string sval; // can't put string into a union
};
See also boost::any at http://boost.org/doc/html/any.html
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925
.
- Follow-Ups:
- Prev by Date: Re: Pipeline Architecture Implementation
- Next by Date: Re: Executing a exe
- Previous by thread: Re: Pipeline Architecture Implementation
- Next by thread: Re: What's the best way? STL containers and template.
- Index(es):
Relevant Pages
|