C++ is a strongly typed language. You can't write a function that
returns different types based on its input argument. The only way is to
use a variant type. There are many existing implementations, or you can
write your own. The key is to write a class that can change its type
dynamically. The easiest way is using a union:
struct MyVariant
{
enum VarType { IntType, CharType, StringType };
VarType type;
union
{
int i;
char c;
char* s;
};
};
Of course this is unfinished, but it gets you started. Take a look at
the VARIANT data type in COM, although it's pure C, it also has a C++
wrapper in ATL.
Note that variants introduce complexity and runtime overhead to your
code. Obviously a GetVariable function like yours will run way slower
than accessing x, y, and z directly.
Tom
batista wrote:
Hello to ALL,
I'll explain my problem by pseudo code
class A
{
int x;
char y;
string z;
}
class B
{
GetVariable(int i)
{
A a = new A();
//Now I want to return the ith varaible
//of class A
}
}
class C
{
GetVar()
{
B b = new B();
b.GetVariable(0) //it shud return x
b.GetVariable(1) //it shud return y
b.GetVariable(2) //it shud return z
}
}
Now how do I implement the GetVariable(int i), in VC++
The reason I have class B is because there are lot's of classes
like class A, and i don't want to edit them all.
Any Suggestions...
Thanks In advance...
Cheers...
Bye