What you're describing sounds like Variants, i. e. a class that serves as a wrapper for variables of varying type. You can implement these without classes, using
union
, or google for existing implementations and use those. I believe Managed C++ even has such a class, but I'm not working with that, so I may be wrong.
Solution with union:
struct SVariant {
enum { VAR_DOUBLE, VAR_INT } vartype;
union {
double x;
int i;
} value;
};
void setVariant(SVariant* v, double value) {
v.value.x = value;
v.type = VAR_DOUBLE;
}
void test(SVariant* v) {
if (v.type == VAR_DOUBLE) {
do_double(v.value.x);
else if (v.type == VAR_INT) {
do_int(v.value.i);
}
}
Anyway, in most cases Variants are a bad idea: they place the onus of distinguishing the actual types and deciding what to do with the values on the caller. It is exactly the opposite of what OO-design is about, and so I feel it's wrong to even try and create a class framework for such a concept.
What you should do is create a class for each type of variable, and then put the functions that operate on the values into these classes! You could implement it like this:
class CBase {
public:
virtual ~CBase();
virtual void do_work() = 0;
};
class CDerived1 : public CBase {
private:
double x_;
public:
CDerived1(double x);
~CDerived1();
void do_work();
};
class CDerived2 : public CBase {
private:
int i_;
public:
CDerived2(int i);
~CDerived2();
void do_work();
};
CDerived1::CDerived1(double x) : x_(x) {
}
void CDerived1::do_work() {
do_double(x_);
}
CDerived2::CDerived2(int i) : i_(i) {
}
void CDerived2.do_work() {
do_int(i_);
}
void test(CBase* b) {
b->do_work();
}
void main_test() {
CDerived1 d1(3.14);
CDerived2(42);
test(d1);
test(d2);
}
In this solution, the caller
test()
just calls do_work(), and that's it. it doesn't need to know what derived classes exist, and what to do with each value, the implementation of each derived class does it for you. The caller doesn't even need to know there *are* any derived classes, although the '=0' in this example is a dead giveaway.