[英]Why can't I call operator() on temporary objects directly?
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. 和我的编译器
(g++ 6)
拒绝代码抱怨a
阴影的参数。 However, if I try to explicitly call operator()
, it works as expected. 但是,如果我尝试显式调用
operator()
,它会按预期工作。
It seems that g++
will ignore the parentheses and see the statement as a declaration. 似乎
g++
将忽略括号并将该语句视为声明。
Is this the specified or expected behavior? 这是指定的还是预期的行为?
This is one of those icky parsing rules which catches you every now and again. 这是那些icky解析规则之一,一次又一次地抓住你。 As you suggest,
B(a)(2);
如你所知,
B(a)(2);
is actually equivalent to B a(2);
实际上相当于
B a(2);
, so your code tries to initialize a B
with an int
. ,所以你的代码试图用
int
初始化一个B
To fix this, you can use C++11's uniform initialization: 要解决此问题,您可以使用C ++ 11的统一初始化:
B{a}(2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.