fast-reflexes
fast-reflexes

Reputation: 5186

C++ non-function typedef with parentheses

How come I can always add a pair of parentheses to a typedef and what does it mean?

#include <iostream>
#include <typeinfo>

int main() {
    typedef int td;
    std::cout << typeid(td).name() << std::endl;
    std::cout << typeid(td()).name() << std::endl;
    return 0;
}

Outputs:

i
FivE

Upvotes: 1

Views: 296

Answers (2)

T.C.
T.C.

Reputation: 137325

td() can be one of two things according to the grammar:

  • It can be a type-id, naming the type "function taking no parameter and returning td"
  • It can be an expression, meaning a value-initialized td.

The typeid operator can be used with both a type-id and an expression. This ambiguity is resolved by the standard in favor of it being a type-id (§8.2 [dcl.ambig.res]/p2):

The ambiguity arising from the similarity between a function-style cast and a type-id can occur in different contexts. The ambiguity appears as a choice between a function-style cast expression and a declaration of a type. The resolution is that any construct that could possibly be a type-id in its syntactic context shall be considered a type-id.

In contexts where a type-id is not allowed, td() would be a value-initialized td object. For instance:

void foo(int i = int()); 

is equivalent to

void foo(int i = 0); 

Upvotes: 3

Jarod42
Jarod42

Reputation: 217448

td() is int(): a function returning int taking no parameter.

Upvotes: 4

Related Questions