On Wed, Oct 15, 2008 at 09:54:36PM +0300, Lasse Kärkkäinen wrote:
> The following problem is very common when dealing with iterators,
> function objects and/or algorithms in C++.

Yes, I ran into this issue myself earlier this week.  It's a more
general problem, striking whenever the arguments to a constructor
are themselves constructor calls.

> This is a simple test case:
> 
> #include <iostream>
> #include <iterator>
> #include <string>
> 
> int main() {
>   using namespace std;
>   typedef istreambuf_iterator<char> isbi;
>   string str(isbi(cin), isbi());           // Line 8
>   cout << str << endl;                     // Line 9
> }
> ...
> The problem here is that the C++ standard requires line 8 to be
> interpreted as a declaration of a function named str, returning string
> and taking two arguments of type isbi (the first one is named cin and
> the second one is anonymous). The extra parenthesis around variable
> names are ignored.
> 
> However, since it is not conventional to use parenthesis around variable
> names in function declarations, this problem could be analyzed by GCC,
> issuing a proper warning.

Good idea.

> My suggestion:
> 
> Whenever a function declaration with parenthesis around parameter names
> is seen, issue a warning:
> 
> <file>:<lineno>: warning: '<symbolname>' is interpreted as a function
> declaration, but it looks like a variable definition (put parenthesis
> around '<first argument>' to make it so)

But the wording of the warning needs work, as "make it so" is ambiguous here.
Perhaps

<file>:<lineno>: warning: '<symbolname>' is interpreted as a function
declaration; put parentheses around the first argument to make it
a variable definition

Another way to get the correct interpretation is to write

    string str = string(isbi(cin), isbi());

> Note: the case of variable initialization without arguments (also
> interpreted as a function declaration) cannot be diagnosed in this
> manner. Therefore no warning should be issued on this: string str();
> People generally learn to write just string str; rather quickly.

string str();

looks like a function declaration, so users are less likely to write
this when declaring a string.

Reply via email to