1

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.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304

2 Answers2

2

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

See Most vexing parse

Community
  • 1
  • 1
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • +1 and thanks. The compiler message could be a little clearer then by saying "conflicting declaration Fun a(b)"! – TemplateRex Oct 05 '12 at 08:54
  • 1
    @rhalbersma, C++11 has extended initializer lists to make initialization unambiguous. `Fun{a}(b)` will be parsed as expected. – Vikas Oct 05 '12 at 09:09
1

Simple example to understand function declaration syntax:

#include <iostream>

void (foo)(int a) {
   std::cout << a << std::endl;
}

int main() {
   foo(5);
}

So in your case you have to use this:

Fun(a).operator()(b); 
(Fun(a))(b);
fasked
  • 3,555
  • 1
  • 19
  • 36