Search code examples
c++constructorargumentsmost-vexing-parsefunction-object

Parsing ambiguity in a call to a temporary function object


I suspect that in the code below, a call to a temporary function object with both a constructor argument and a function call operator argument is somehow ambiguous due to a most-vexing-parse issue.

#include <iostream>

class Fun
{
public:
        explicit Fun(int i): v_(i) {}

        void operator()(int j) const 
        { 
                std::cout << (v_ + j) << "\n"; 
        }

private:
        int v_; 
};

int main()
{
        int a = 1;
        int b = 2;

        Fun(a)(b);   // ERROR: conflicting declaration 'Fun a'
        (Fun(a))(b); // OK: prints 3
        return 0;
}

Output on Ideone.

Adding parentheses like (Fun(a))(b) fixes the problem, but I can't quite understand how Fun(a)(b) can be parsed as a declaration Fun a.


Solution

  • Unfortunately Fun(a)(b); can be parsed as Fun a(b); which is a declaration, and not a temporary object.

    See Most vexing parse