What I want to do can be summarized into the following code:
struct A{};
struct B{
A& a;
B(A& a) noexcept : a(a){}
int operator()(int) {}
};
int main(){
A a;
B(a)(2);
}
And my compiler (g++ 6)
rejected the code complaining that a
shadows a parameter. However, if I try to explicitly call operator()
, it works as expected.
It seems that g++
will ignore the parentheses and see the statement as a declaration.
Is this the specified or expected behavior?
The function call operator is denoted by “()” which is used to call function and pass parameters. It is overloaded by the instance of the class known as a function object. When the function call operator is overloaded, an operator function is created that can be used to pass parameters.
A temporary object is an unnamed object created by the compiler to store a temporary value.
The function call operator, when overloaded, does not modify how functions are called. Rather, it modifies how the operator is to be interpreted when applied to objects of a given type.
This is one of those icky parsing rules which catches you every now and again. As you suggest, B(a)(2);
is actually equivalent to B a(2);
, so your code tries to initialize a B
with an int
.
To fix this, you can use C++11's uniform initialization:
B{a}(2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With