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++的核心。 例:
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;
不过,可以通过引用的静态强制转换来绕过限制。
相关文章:
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 铸造标准::有没有回到原来的类型
- 有没有办法提示用户使用哪种数据类型作为模板 c++
- 有没有办法通过使用十进制 ASCII 代码自动类型扣除来获取字符?
- 有没有办法一次声明相同类型的多个对象,并通过一个表达式立即使用相同的右值初始化它们?
- C++如果采用类类型的函数被传递派生类型,有没有办法给出错误?
- 有没有办法避免为 std::variant 类成员中的所有类型编写构造函数?
- 有没有办法改变概念中的复合需求返回的类型?
- 有没有办法检查发送到变量的值是否是正确的类型,而它已经在该变量下?
- 有没有办法让C++函数采用具有相同成员的两种不同类型?
- 有没有办法将字符类型转换为整数?
- 有没有办法将输入类型包装到C++中的模板类?
- 有没有办法同时将一个类型分配给C++中的多个模板?
- 有没有办法根据 lambda 参数返回类型部分专用化我的模板化函数?
- 有没有办法在函数 c++ 中输入任何数据类型?
- 有没有一种方法可以使用SFINAE来检测一个类型是否实现了给定的抽象基类
- 有没有办法在没有reinterpret_cast的情况下保存多种类型的指针?
- 有没有办法在 C++17 中创建编译时类型映射以进行类型检查?
- 有没有办法在 c++ 中制作类型变量?
- 有没有办法通过插入新类型名称而不是 int 来使用 2 位大小类型而不是 int?