"There is no “reference-to-member” type in C + +"、std::bind 和 boost::bind 在同一条船上

"There is no “reference-to-member” type in C + +", std::bind and boost::bind are in the same boat

引用标准(2003)版本(我认为最近的其他人也这么说)8.3.3 的最后,大胆强调是我的:

A pointer to member shall not point to a static member of a class (9.4), a member with reference type, or “cv void.” [Note: see also 5.3 and 5.5. The type “pointer to member” is distinct from the type “pointer”, that is, a pointer to member is declared only by the pointer to member declarator syntax, and never by the pointer declarator syntax. There is no “reference-to-member” type in C + +. ]

但是我看到很多

boost::bind(&SomeClass::SomeMemberFunction, this, _1)

以及

std::bind(&SomeClass::SomeMemberFunction, this, std::placeholders::_1)

etc 像一个魅力一样工作,涉及 &SomeClass::SomeMemberFunction 似乎是对成员函数的引用。

标准是简单的说例如

int (SomeClass::&RefOnSomeMemberFunction) (int) = SomeClass::SomeMemberFunction

不是该语言的有效断言,还是有更多?

C++ class 的成员函数隐式使用 this 作为第一个参数。 所以 std::bind(&SomeClass::SomeMemberFunction, this, std::placeholders::_1) 可以解释为:

  1. 获取SomeClass::SomeMemberFunction的函数指针地址;
  2. 使用this作为函数的第一个参数,这里this是对象的地址;
  3. 使用std::placeholders::_1作为第二个参数。

然后你得到一个 functor,它将调用 objectSomeMemberFunction 和占位符 _1.

你对措辞的理解是正确的。以下格式错误:

int (SomeClass::&RefOnSomeMemberFunction) (int) = SomeClass::SomeMemberFunction;

事实上,如果你看语法规则,只有

nested-name-specifier * attribute-specifier-seqopt cv-qualifier-seqopt D1


您对调用 boost::bindstd::bind 时发生的情况的理解存在缺陷。在此上下文中,unary & 是 addressof 运算符,它产生指向成员(函数)的 pointer。该指针在您引用的段落中定义。