c++ - 允许继承类使用相同的功能
问题描述
我有一个由 EulerAngle 类继承的 Vector 类。我希望能够在 EulerAngle 对象上使用 Vector 类中的运算符函数,而不必重写 EulerAngle 类中的运算符并尽可能将 Vector3 更改为 Angle。我怎么能这样做?
class Vector3 {
public:
float x, y, z;
// ctors...
__forceinline Vector3() : x{}, y{}, z{} {
__forceinline Vector3( float x, float y, float z ) : x{ x }, y{ y }, z{ z } {
}
// functions...
// operators...
__forceinline Vector3 &operator +=( const Vector3 &other ) {
x += other.x;
y += other.y;
z += other.z;
return *this;
}
__forceinline Vector3 &operator +=( float scalar ) {
x += scalar;
y += scalar;
z += scalar;
return *this;
}
__forceinline Vector3 operator +( float scalar ) const {
return Vector3( x + scalar, y + scalar, z + scalar );
}
__forceinline Vector3 operator +( const Vector3 &other ) const {
return Vector3( x * other.x, y * other.y, z * other.z );
}
}
class EulerAngle : public Vector3 {
private:
};
// example, MSVC says this is an error and that there is no suitable conversion from EulerAngle to Vector3
EulerAngle ang = { 1.f, 1.f, 1.f };
ang += 5.f
在几个答案之后,我添加了以下代码来完成这项工作。但是我仍然想知道是否有更好的方法来实现这一点?
class EulerAngle : public Vector3 {
public:
using Vector3::Vector3;
__forceinline EulerAngle( const Vector3 &other ) : Vector3( other ) {
}
};
解决方案
当它不是从.Vector3
Vector3
template<typename T>
operator T() const
{
static_assert(std::is_base_of<Vector3, T>::value, "T is not inherited from Vector3");
return T{x,y,z};
}
现场演示
==================================================== ==============
添加在
随着C++20
和概念的引入,上面的代码可以重写为:
template<typename T>
requires std::DerivedFrom<T,Vector3>
constexpr operator T() const
{
return T{x,y,z};
}
现场演示
推荐阅读
- java - Java 9 如何避免拆分包
- angular - NavController 在 Ionic 4 中不起作用
- javascript - 计算表格列
- outlook - 将加载项列入 Outlook 移动列表白名单的审批流程是什么?
- javascript - 在反应中,如何将对象存储在数组中并将数组索引迭代1?
- reactjs - 类方法React.Component的类型注解怎么写?
- amazon-web-services - AWS S3 在文件名中出现锚点问题#
- angular-material - Angular Material Select 未显示默认选择
- python - 将集合转换为列表时出现参数错误
- android-studio - android studio:minSdkVersion 22 错误