Getting the type of a variable?

F

fotzor

Hi,
is it somehow possible to get the type of a variable in a macro?
example:

#define SOME_MACRO(x) // what's the type of x???

i guess the type-information is lost but i can't use a template here
 
V

Victor Bazarov

fotzor said:
is it somehow possible to get the type of a variable in a macro?
example:

#define SOME_MACRO(x) // what's the type of x???

i guess the type-information is lost but i can't use a template here

No. The type information is not lost. It just doesn't exist when the
preprocessor is active.

You can get some information about the type using 'typeid' operator.
You will need to #include <typeinfo>, enable the RTTI (some compilers
have it disabled by default), and take it from there. RTFM on typeid.

Be warned, though, that if you feel the need to know the type of some
object, it is most likely that your design is flawed. A good program
does not need to know the type, it just behaves correctly with all the
types known only to the compiler.

Victor
 
C

CG

You can use the typeid operator.

For instance:

///////////////
class Car;

Car x = new Car();

cout << typeid( x ).name() << endl;
///////////////

Should output "Car"!
 
R

Richard Herring

CG said:
You can use the typeid operator.

For instance:

///////////////
class Car;

Car x = new Car();

cout << typeid( x ).name() << endl;
///////////////

Should output "Car"!
Or almost anything else :-(

According to 18.5.1 the result is merely "a name for the type", and is
otherwise unspecified and may differ between programs.
 
K

Karthik Kumar

CG said:
You can use the typeid operator.

For instance:

///////////////
class Car;

Car x = new Car();

typeid is part of RTTI (Run-time type identification) mechanism
in C++. As the name says, it applies only for dynamically bound
objects.

So the above should be -

Car * x = new Car()

or

Car & x = y;

where y is an object of a type 'Car' or another type T derived from Car.
 
O

Old Wolf

is it somehow possible to get the type of a variable in a macro?
example:

#define SOME_MACRO(x) // what's the type of x???

There is a non-standard but common extension operator called "typeof",
for example:

typeof(x) *ptr = &x;

There are proposals for something like this to be added to
future C++ standards.
i guess the type-information is lost but i can't use a template here

You could use a template:

template<typename T>
void some_function(T &t)
{
..........
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,183
Messages
2,570,968
Members
47,517
Latest member
TashaLzw39

Latest Threads

Top