开发者

Why is C++ "typename" required even in cases where there is no parsing ambiguity? [duplicate]

开发者 https://www.devze.com 2023-04-13 06:33 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Use of typename keyword with template function parameters
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Use of typename keyword with template function parameters

Use of typename keyword with typedef and new

I understand why C++ has the typename keyword. The parsing of certain token sequences, such as

qwert * yuiop;
asdfg(*hjkl)(zxcvb);

depends on whether certain identifiers (in this case, qwert, asdfg and zxcvb) refer to types or to values. So in templates, sometimes it needs to be told so that it can parse the template definition.

template<class Qwert> void yuiop() {
    typename Qwert::asdfg * zxcvb;  // declare a pointer of type Qwert::asdfg
    Qwert::asdfg * hjkl;            // multiply Qwert::asdfg by hjkl
}

However, there are cases where the syntax can only accept a type, yet typename is still required.

template<class Qwert> void yuiop(Qwert::asdfg) {
    Qwert::asdfg hjkl;
}

This doesn't compile. It seems that typical compilers assume Qwert::asdfg is a variable or constant and so throw a syntax error. But why?

  • On the first line, the parsing context guarantees that we are dealing with a function signature, not a function call, and C++ (unlike C) doesn't allow a parameter to be declared in a function signature开发者_运维问答 without a type, and so what follows the open bracket must be a type.
  • Where two identifiers are juxtaposed as on the second line, the first identifier must always denote a type.

The essence of my question is: Why doesn't the C++ standard allow type/value ambiguities to be resolved from the parsing context in cases like these?

(Note: the nearest thing I've found online to a standard states something to this effect near the bottom of page 301. I don't know whether any actual standards are different in this respect.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号