函数未解析为基类重载
Function not resolving to base class overload
我尝试在这个(简化的)示例中使用 CRTP:
基类:
template <class Derived>
class Base
{
public:
int method(int in, int& out2)
{
return derived().method(in, out2);
}
int method(int in)
{
int dummy;
return this->predict(in, dummy);
}
protected:
Base() {}
private:
Derived& derived()
{
return *static_cast<Derived*>(this);
}
};
派生类:
class Derived : public Base<Derived>
{
public:
int method(int in, int& out2)
{
// Logic here
}
};
问题是,当我尝试将method(int in)
与Derived
类的实例一起使用时,例如:
Derived d;
int res = d.method(5);
编译器(在这种情况下为 icc,但也尝试使用 msvc)给了我以下错误:
错误 #165:函数调用中的参数太少
编译器似乎没有意识到存在一个重载,它只从Base<Derived>
类中获取一个参数(Derived
从中公开继承,所以我认为它应该是可访问的)。
不确定我在这里错过了什么,任何提示都将不胜感激。
Derived::method
的存在意味着编译器在尝试绑定调用时不会考虑Base::method
的重载。若要解决此问题,请将using Base::method;
添加到派生类:
class Derived : public Base<Derived>
{
public:
using Base::method;
int method(int in, int& out2)
{
// Logic here
}
};
当一个非虚函数被定义为与Base::method
同名时,它会掩盖Derived
类中的Base::method
,这也被称为名称隐藏。
为了防止这种情况,您必须使用 using
运算符显式提及带有类的方法名称,即您的Derived
类代码应修改为:
class Derived : public Base<Derived>
{
public:
using Base::method; //makes the 'method' declaration of Base class
//visible here as well.
int method(int in, int& out2)
{
// Logic here
}
};
相关文章:
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 如何在基类指针向量的元素上应用重载的多态函数
- 模板基类中的重载运算符
- 从多个模板化基类派生时出现"隐藏重载的虚函数"警告
- 将基类的成员函数重载到其他派生类C++
- 如何从派生类访问基类中的重载运算符?
- C++ 继承:基类中重载 operator+ 的 2 次在派生类中无法正常工作
- 派生类不能用另一个基类的成员重载基类中的私有成员
- 基类和派生类的虚拟插入运算符重载
- C++ 模板:重载时找不到基类类型参数方法
- 基类和派生类中的模板成员之间的重载解析
- 派生类 插入和提取运算符重载以及基类与派生类之间的强制转换
- 从抽象基类中获取重载函数
- 什么更有效率?在重载函数中或通过在基类函数中检查对象类型来实现
- 为什么无法访问基类的函数重载
- SWIG:在派生类中处理基类重载方法
- 如何使用共享基类重载派生类的运算符<<?
- 函数未解析为基类重载
- 如何使用派生类实例调用基类重载的func,
- 从父类调用基类重载操作符