成员函数具有隐式this指针参数.为什么std::function接受这个签名,那么,S是一个简单的类?(完整样本)
std::function<void(S &)> func = &S::foo;
Run Code Online (Sandbox Code Playgroud)
调用它也有效,并区分对象:
S s1 = {5};
S s2 = {6};
func(s1); //prints 5
func(s2); //prints 6
Run Code Online (Sandbox Code Playgroud)
我通常期望它需要一个指针,它也可以工作:( 完整样本)
std::function<void(S * const)> func = &S::foo;
S s1 = {5};
S s2 = {6};
func(&s1); //prints 5
func(&s2); //prints 6
Run Code Online (Sandbox Code Playgroud)
当隐式this参数是指针时,当我将引用传递给成员函数时,为什么第一个工作正常?
因为std::function设计正确.this作为指针的事实是历史事故和成员函数内部的细节.事实应该对功能用户的设计决策没有影响.
std::function当签名中的第一个参数类型是引用时,设计者决定接受成员函数.
std::function<SIG>可以由许多行为类似于函数的东西构造,并将它们转换为适当的std::function对象。
在这种情况下,void S::foo()其行为很像一个函数void foo_x(S&)(因为它们都需要S调用,并且可能需要修改S,不返回任何内容)。因此std::function<void(S&)>提供了一个构造函数来将成员函数转换为函数对象。IE
std::function<void(S &)> func = &S::foo;
Run Code Online (Sandbox Code Playgroud)
使用构造函数(例如std::function<void(S&)>( void(S::)() ))来创建相当于以下内容的内容:
void foo_x(S & s ) { return s.foo(); }
std::function<void(S&)> func = foo_x;
Run Code Online (Sandbox Code Playgroud)
相似地,
std::function<void(S * const)> func = &S::foo;
Run Code Online (Sandbox Code Playgroud)
相当于
void foo_x(S * const s ) { return s->foo(); }
std::function<void(S* const )> func = foo_x;
Run Code Online (Sandbox Code Playgroud)
通过像std::function<void(S* const )>( void(S::)() ).