简体   繁体   中英

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

td()int() :不带参数返回int的函数。

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM