[英]Why does a member function needs '&' (e.g. in std::bind)?
When I was playing with std::bind
from the C++11 -standard I recognized the following would be allowed by the compiler: 当我从C ++ 11- standard开始使用
std::bind
,我发现编译器允许以下内容:
class Foo
{
public:
void F();
int G(int, int);
};
void Foo::F()
{
auto f = bind(&Foo::G, this, _1, _2);
cout << f(1,2) << endl;
}
int Foo::G(int a, int b)
{
cout << a << ',' << b << endl;
return 666;
}
But if I eliminated the '&' in front of the Foo::G
in the bind
-line, I would get some compiler errors (using MinGW 4.7). 但是如果我在
bind
消除了Foo::G
前面的'&',我会得到一些编译器错误(使用MinGW 4.7)。
Why is Foo::G
not valid as a pointer to a member function, although H
and &H
would both work for "usual" functions? 为什么
Foo::G
无效作为指向成员函数的指针,尽管H
和&H
都适用于“通常”函数?
LG ntor LG ntor
& is required to take address of a member function, some compilers will allow you to omit the same but it is non-standard and at times confusing. &需要获取成员函数的地址,一些编译器将允许您省略相同但非标准并且有时令人困惑。
you can read about member function pointers in here: http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible 你可以在这里阅读有关成员函数指针的内容: http : //www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible
I take it that one of the reasons could have been consistency. 我认为其中一个原因可能是一致性。 Recall that within a class, you can say
回想一下,在课堂上,你可以说
MyClassOrOneOfItsBases::memberFunction();
It compiles fine, since the qualified name names the member function, instead of forming a pointer to member. 它编译得很好,因为限定名称命名成员函数,而不是形成指向成员的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.