C++如果采用类类型的函数被传递派生类型,有没有办法给出错误?

In C++ is there a way to give error if a function that takes a class type is passed a derived type instead?

本文关键字:类型 有没有 错误 出错 派生 如果 C++ 函数      更新时间:2023-10-16

如果采用类类型的函数被传递派生类型,有没有办法给出错误? 找不到这个的副本,也许是因为多态性是C++的核心。 例:

class Base
{
int a;
};
class Derived : public Base
{
};
int MySpecialFunc(Base &_a) // I want an error/not compile if 'Derived' is passed instead of 'Base'
{
return 1;
}

您可以在运行时使用typeid进行精确的类型检查。

但是,我会严重质疑这种检查的潜在动机。 人们经常建议继承与利斯科夫替代原则保持一致。

你提出的是,即使一个派生类完全可以李斯科夫替换基类,这个函数也会对这种可替代性进行二次猜测。 它几乎肯定会限制基类的可扩展性。

int MySpecialFunc(Base& a)
{
if (typeid(a) != typeid(Base)) 
{
throw std::runtime_error("Type is not exactly `Base`.");
}
// ...
}

只要您只需要限制一组有限的类型,并且只需要防止直接传递,那么重载就可以了:

int MySpecialFunc(Derived &) = delete;

不过,可以通过引用的静态强制转换来绕过限制。

相关文章: