gpt4 book ai didi

c++ - 指向父类成员方法的指针

转载 作者:行者123 更新时间:2023-12-02 18:48:21 26 4
gpt4 key购买 nike

我正在尝试让以下简单的代码工作:

#include <functional>
#include <iostream>

class Parent {
public:
void method(int a) {
std::cout << "Parent::method(" << a << ")" << std::endl;
}
};

class Child : public Parent {
public:

};

template <typename T>
std::function<void()> test(T* v, void(T::* fn)(int)) {
return std::function<void()>([v, fn](){
v->fn(10);
});
}

int main() {
Child c;

std::function<void()> fn = test(&c, &Child::method);

fn();

return 1;
}

但出现以下错误:

note:   template argument deduction/substitution failed:
note: deduced conflicting types for parameter 'T' ('Child' and 'Parent')
std::function<void()> fn = test(&c, &Child::method);

如果我将指针更改为 Parent::method,我也会遇到同样的问题。既然 Child "is"parent,为什么编译器无法推导出这个模板?

谢谢!

最佳答案

Child "is a" parent

这是面向对象意义上的。但模板参数推导主要是关于类型身份

&Child::method 命名 Parent 的成员。它可以在 Child 中访问,但它是在 Parent 中声明的。因此,从该成员中唯一可用的 T 扣除是 Parent。另一方面,指针将 T 推断为 Child。这里T身份无法唯一确定。所以是推演失败。

但是我们仍然可以通过调整来编写您的函数模板:

template <class C, class P>
std::function<void()> test(C* v, void(P::* fn)(int)) {
return std::function<void()>([v, fn](){
(v->*fn)(10);
});
}

现在,这些类是在它们自己的上下文中推导的,不会影响其他类。这样就足够了(因为 (v->*fn)(10) 对于不相关的类来说格式不正确)。但是可以进行额外的检查以使过载sfinae变得友好。

关于c++ - 指向父类成员方法的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67126233/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com