指向成员函数签名的指针中缺少"this"指针
Missing "this" pointer in pointer to member function signature
我正在写一个小的信号/插槽类。 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;
}
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 关于C++中具有多重继承"this"指针的说明
- Doees the 'this' 指针参与虚函数的多态行为
- 指针'this+1' C++中指的是什么?
- 为什么使用指向函数的指针调用虚函数时不需要指针"this"?
- Lambda 函数捕获错误的指针"this"
- 调用类的方法时,类的指针"this"变为 null C++
- 指针'this'可以是共享指针吗?
- 如何在C++中为指针'this'赋值
- C++:指针"this"没用吗?
- 指针"this"有什么问题?
- 将指针'this'传递为 LPARAM
- 错误 C2663:指针'this'重载没有合法转换
- C++ : 了解指针"this"
- 更改对象的指针'this'以指向不同的对象
- C++编译器是为所有成员方法生成指针"this"还是仅为引用成员的方法生成指针?
- 使用指针和不使用指针"this"有区别吗?
- 将enable_shared_from_这个基于类的指针(this)存储在itelf中
- 创建指向对象的指针"this"
- 如何在类中取消初始化指针"this"?