指向成员函数签名的指针中缺少"this"指针

Missing "this" pointer in pointer to member function signature

本文关键字:指针 this 成员 函数      更新时间:2023-10-16

我正在写一个小的信号/插槽类。 dispatch 函数获取类的实例和指向实例类型成员的指针,并将其存储在一个std::function中,实例指针绑定到第一个参数,并std::bind提供this指针。我的主要问题是我是否误解了 c++ 的规则,或者我的编译器没有按预期运行。

template <class Signal, class ... ArgTs>
class SignalDispatcher {
//...
template <class Class>
void dispatch(const Signal& signal, Class* target, void (Class::*slot)(Class*, ArgTs...));
//...
};

然后,如果我使用这样的参数调用调度函数

SomeStruct instance;
SignalDispatcher<int, some_type> dispatcher;
dispatcher.dispatch(1, &instance, &SomeStruct::member_function);

我的编译器说传递的成员函数签名是

void (Class::*)(ArgTs...)

而不是预期的

void (Class::*)(Class*, ArgTs...)

进而导致类型不匹配和编译失败。

我的编译器是G ++ 6.3.0

编译器是对的。不要将this指针指定为指向成员的指针的参数。它由用于定义和调用它的语法提供。

void (Class::*slot)(ArgTs...);
       ^---- this is a pointer of Class type.
Class c;
(c.*slot)(args...);
 ^--- this will point to c.

成员函数指针有不同的语法是有原因的。(有几个原因,但这是其中之一。

如您所注意的,不可见的this指针在后台传递,但这并不意味着在传递成员函数指针时需要自己指定它。用于声明成员函数指针变量的语法

return_type (class_name::*variable_name)(/* arguments */);

其中已经有类名。这样编译器就知道要传递哪种指针作为this


例:

struct MyTest
{
    void func1() {}
    int func2(int arg1) { return arg1; }
};
int main()
{
    // One way
    using func1_t = void (MyTest::*)();
    using func2_t = int (MyTest::*)(int);
    func1_t one_func1_ptr = &MyTest::func1;
    func2_t one_func2_ptr = &MyTest::func2;
    // Another way
    void (MyTest::*another_func1_ptr)() = &MyTest::func1;
    int (MyTest::*another_func2_ptr)(int) = &MyTest::func2;
    // Or an easy way (available in some situations)
    auto easy_func1_ptr = &MyTest::func1;
    auto easy_func2_ptr = &MyTest::func2;
}