Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining the type of an expression

Tags:

c++

c

Sometimes I need to learn the type of an expression while programming in C or C++. Sometimes there's a good IDE or existent documentation to help me, but sometimes not. I often feel such a construct could be useful:

void (*myFunc)(int);
printf("%s", nameoftype(myFunc)); //"void (*)(int)"
int i, unsigned int u;
printf("%s", nameoftype(i+u));    //"unsigned int"

This is especially true for C++; think accessors of const objects - do they return a const reference or a copy? Think dynamic casts and templated classes.

How can I do this? (i.e. learn the type of an expression)

I use GCC but as far as I know, it does not have such an extension. So I guess I'm curious as to how people solve this problem. (Both compile-time and runtime solutions welcome.)

like image 754
aib Avatar asked May 06 '09 13:05

aib


2 Answers

Sometimes I just do:

int ***a = expression;

and look for the "<expression type> cannot be assigned to pointer-to^3 int" error. This seems to be the most portable workaround.

like image 150
aib Avatar answered Sep 18 '22 18:09

aib


What are you looking for? Automatic type inference or looking for the type so you can declare a variable correctly manually? (your own answers look like you want to have the second one). In this case, consider using Geordi:

<litb> make type pointer to function taking pointer to array of 10 int returning void
<geordi> void (*)(int (*)[10])

<litb> geordi: { int a = -1; unsigned int b = 0; cout << ETYPE(a + b), ETYPE_DESC(a + b), (a + b); }
<geordi> rvalue unsigned int, rvalue unsigned integer, 4294967295

<litb> geordi: << TYPE_DESC(void (*)(int (*)[10]))
<geordi> pointer to a function taking a pointer to an array of 10 integers and returning nothing

Automatic type inference is not currently possible without helper libraries like boost.typeof, which will use compiler extensions like __typeof__ for GCC. Next C++ will get auto (with different semantics than current auto) and will be able to do that, together with decltype to get the type of an expression.

If you can live with getting out of local context, you can always create a function template like this:

template<typename T> void f(T t) { /* ... */ }
int main() { int a = -1; unsigned int b = 0; f(a + b); }
like image 38
Johannes Schaub - litb Avatar answered Sep 17 '22 18:09

Johannes Schaub - litb