JosephConrad
JosephConrad

Reputation: 688

C++ preprocessor __typeof

Recently I have found and I have started using in my preprocessor the following code:

#define FOREACH(i,s) for(VAR(i,(s).begin()); i != (s).end(); i++)
#define VAR(a,b) __typeof(b) a=(b)

what makes my iterating easier. But unfortunately I don't fully understand the second line, especially the __typeof keyword (and why those two underscores are used). I also assumed that the whole expression __typeof(b) is a type casting, but when I take it in parenthesis, why it does not work?

Upvotes: 1

Views: 2478

Answers (2)

Just assume some real values for i and s to see what it does:

std::list<int> list;
FOREACH(i, list)

This will resolve in the macro FOREACH(i, list):

for(VAR(i, (list).begin()); i != (list).end(); i++)

Now resolve macro VAR(i, (list).begin()):

__typeof((list).begin()) i = (list).begin();

Where __typeof gets the type of the Argument (list).begin() which is in this case std::list<int>::iterator

std::list<int>::iterator i = (list).begin();

Now insert this into the for and get:

for(std:list<int>::iterator i = (list).begin(); i != (list).end(); i++)

As you see the __typeof part is no typecast but a declaration, so the paranthesis are wrong there.

Also note the many comments on why not to use macros and __typeof in special!

Upvotes: 2

user743382
user743382

Reputation:

__typeof(b) is not a cast. It is non-standard C++ usable with G++, and means "the type of b". In other words, it's a type, and __typeof(b) a=(b); is a definition which defines a as having the same type as b, and is initialised from b. So after int b = 3;, it means int a = b;.

Standard C++11 (which is fairly new and not yet fully implemented by any compiler that I know of) includes a mostly similar feature called decltype.

Upvotes: 4

Related Questions