Parenthesizing Unnamed: Time Series in C ++

Consider the following code:

struct Foo { }; struct Bar { explicit Bar(const Foo&) { } }; int main() { Foo foo; Bar bar(foo); // Okay. Bar(foo); // Will not compile. (Bar(foo)); // Okay. Unnamed temporary requires parenthesis. } 

Why do I need a bracket around the temporary version? What ambiguity do they solve?

My hunch is this: I think the compiler sees Bar(foo) as a declaration for a function, but I'm not sure why this will be so, since foo (instance) is not a type. Consequently, the brackets cause the above expression to be considered as an expression, and not as a foreground declaration.

+4
source share
1 answer

Congratulations on discovering the most unpleasant parsing .

Scott Myers describes this as follows:

In general, the language [C ++] (thanks, unfortunately, its stories) will try to interpret any declaration made in the same way as a function declaration.

In your case, introducing parentheses will blur the parsing, forcing it to become local.

+5
source

Source: https://habr.com/ru/post/1395863/


All Articles