Click to See Complete Forum and Search --> : Find out what class an object belongs to after casting
Pattrick
November 27th, 2002, 01:47 PM
What can I do in order to get this running without using wrapper classes?
class MyClass
{
public:
int x;
int y;
};
void print(void* x)
{
// Here I need to
// know what type x is of
// (int or double or Myclass, or anything...)
}
void main(void)
{
int* x1 = new int(3);
MyClass* x2 = new MyClass();
x2->x = 5;
x2->y = 5;
print(x1);
print(x2);
delete x1;
delete x2;
}
jfaust
November 27th, 2002, 01:54 PM
Nope, can't be done, at least not in any sane way.
A much better approach would be to add a print() method to MyClass, or even better and operator<<.
Jeff
PaulWendt
November 27th, 2002, 03:30 PM
I agree with jfaust. Let the work be done at compile type and
overload operator<<. The compiler WILL call the proper
operator<< for your class; it's called function overloading.
galathaea
November 27th, 2002, 04:12 PM
I don't suggest that its appropriate for your case (where your class can do the work), but there are methods available to check class type at runtime. You could use the type_info class returned by taking the typeid operator on a class, and in fact you can compare them, like
if (typeid(SomeClass) == typeid(int))
{
...
}
but its only there if you cannot find a way to do it using other methods...
Mikey
November 27th, 2002, 05:26 PM
I have to agree to jfaust and PaulWendt:
the only clean solution should be an overloading of the needed types:
void print(int)
void print(double)
...
and for classes (template-design):
template <class TYPE>
void print(TYPE& t)
{
t.print(); // assuming TYPE-class has a func called print()
}
or base-class-design (if prefering heredity):
void print(CBase& rBase)
{
rBase.print(); // assuming rBase-class has a func called print()
}
Mikey ;)
Mikey
November 27th, 2002, 05:54 PM
... but You can also override the ()-operator:
CMyClass operator()(int i)
{
CMyClass oTemp;
put i in oTemp to use it later in print()
return oTemp;
}
CMyClass operator()(double dbl)
{
CMyClass oTemp;
put dbl in oTemp to use it later in print()
return oTemp;
}
using:
int i = 0xffffffff;
double dbl = 0xffffffffffffffff;
CMyClass oMyClass;
print<CMyClass>(oMyClass); // using oMyClass.print()
print<CMyClass>(oMyClass(i)); // first call (int)-op and then oTemp.print()
print<CMyClass>(oMyClass(dbl)); // first call (double)-op and then oTemp.print()
Surely You can play a bit with that to fit it to Your request!
Mikey ;)
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.