与指向继承方法的模板化函数指针一起使用的模板化方法的问题



我似乎不知道一个特定的模板化方法发生了什么。

类似的模板化方法在我的代码库中已经存在了一段时间,并且以与Bar::Bar(IFoo&)相同的方式使用,唯一的区别是传入的函数是继承的。

我有一个接口IFoo,它定义了所讨论的模板化函数。

struct IFoo {
template<class T>
void doSomething(bool (T::*method)(int), T *instance) {
std::cout << (instance->*method)(5) << "n";
}
};

我有一个Bar班,它是另一个班的孩子

struct Parent {
virtual bool setValue(int a) { return true; }
};
struct Bar : Parent { };

当我尝试使用IFoo::doSomething时,编译器只是看不到匹配函数

int main() {
Bar b;
IFoo foo;
foo.doSomething(&Bar::setValue, &b);
}

我收到以下编译器消息
错误:调用"IFoo::doSomething(bool (Parent::*)(int), Bar*)"没有匹配的函数

我真正感到惊讶的是,对于模板化的IFoo::doSomething函数,我没有得到这样的候选建议。

请仅提供C++98解决方案。

正如错误所说,Bar::setValue的类型实际上是bool (Parent::*)(int)。这会干扰doSomething的模板参数推导,因为它有两个需要相同的T。您可以通过强制转换this:来帮助编译器进行推导

int main() {
Bar b;
IFoo foo;
foo.doSomething(&Bar::setValue, static_cast<Parent*>(&b));
}

实时演示

感谢JVApen指出,或者,您可以通过允许两种不同的类型并让Callback进行转换来使doSomething更通用:

template<class T, class U>
void doSomething(bool (T::*method)(int), U *instance);

相关内容

最新更新