模板类、继承和指向成员函数的指针的编译器错误
Compiler error with template classes, inheritance, and pointers-to-member-functions
class A{
virtual int foo1(int a){
return foo1_1(a,filler(a));
}
template<typename FunctionPtr_filler>
int foo1_1(int a, FunctionPtr_filler ptrFn)
{
int b;
b = (this->*ptrFn)(a); // --> compile error: pointer to member type int (B::)(int) incompatible with object type A
return b;
}
protected:
virtual int filler(int a){
return a*a;
}
};
class B: public A{
virtual int foo1(int a){
return foo1_1(a, &B::filler);
}
virtual int filler(int a){
return (a+a);
}
};
他们有什么办法克服这个错误。我想传递填充函数并避免重复代码的代码气味。
我认为这里的问题是您将以下内容作为参数传递:
&B::filler
这是 B
中定义的函数的指向成员函数的指针函数。 在基类中,您尝试将其调用为
(this->*ptrFn)(a);
这里的问题是,如果接收器对象实际上不是类型 B
的对象,这将导致严重的运行时错误,因为您将在类型未B
的对象上调用 B
中的方法。 C++给您一个编译器错误,告诉您这是不允许的。
若要解决此问题,请将调用更改为传入
&A::filler
这是A
中的一个方法,所以任何A
对象都会有这个特定的方法。 C++将自动解析虚拟调用以引用该方法的最派生实现,因此在这种情况下,它应调用函数的B
版本。
希望这有帮助!
相关文章:
- 如何使用指针传递给函数的数组中对象的函数成员
- c++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针