从类模板派生类时使用派生类
Using the derived class when deriving a from a class template
本文关键字:派生 更新时间:2023-10-16
我想为Day
, Month
和Year
编写三个包装器类,基本上只包装int
。我的目标是获得一些类型安全,并且不能意外地切换函数的参数,如void date(int y, int m, int d)
。
完成后,我注意到这三个类共享了很多代码。所以我决定我想从一个基类:Value
派生它们。该基类也将实现operator+
,但它必须返回Year
(或Month
,或Day
),而不是Value
。所以我使用了一点从模板派生的魔法。
你瞧,它几乎起作用了。
operator<<
可以编译,因为' Derived& '可以被解析。
但是operator+=
试图从*this
返回Derived&
,这是一个Value&
。
template<class Derived>
class Value {
protected:
int value_;
public:
explicit Value(int v) : value_{v} {}
int value() const { return value_; }
Derived& operator+=(const Derived& other) {
value_ += other.value_;
return *this; // ERROR!
}
friend ostream& operator<<(ostream& os, const Derived& x) {
return os << x.value_;
}
};
class Year2 : public Value<Year2> {
public:
explicit Year2(int v) : Value<Year2>(v) {} // NOTICE <Year2>
bool isLeap() const { return value_ % 4 == 0; };
};
我有一种感觉,我就要成功了。是否可以使用这种模板派生魔术并实现操作符+= ?此外,令我惊讶的是,我的gcc-4.9.0不知道我如何调用基构造函数。
class Year3 : public Value<Year3> {
public:
explicit Year3(int v) : Value(v) {} // NOTICE no <...>
bool isLeap() const { return value_ % 4 == 0; };
};
我做了一些错误的基础c'tor调用?还是gcc?还是有区别?
您可以使用static_cast
this返回正确的指针。
return *(static_cast<Derived*>(this));
或
return static_cast<Derived&>(*this);
然而,这似乎是不必要的。看起来你并不是真的想让Value类成为一个模板。这有什么原因吗?
这还不够吗?
class Value {
protected:
int value_;
public:
explicit Value(int v) : value_{v} {}
int value() const { return value_; }
Value& operator+=(const Value& other) {
value_ += other.value_;
return *this;
}
friend ostream& operator<<(ostream& os, const Value& x) {
return os << x.value_;
}
};
class Year2 : public Value {
public:
explicit Year2(int v) : Value(v) {}
bool isLeap() const { return value_ % 4 == 0; };
};
int main()
{
Year2 y1(1), y2(2);
y1 += y2;
cout << y1;
return 0;
}
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 在派生函数中指定void*参数
- 如何通过派生类函数更改基类中的向量
- 如何委托派生类使用其父构造函数?
- 如何使用单独文件中的派生类访问友元函数对象
- 派生类销毁的最佳实践是什么
- 如何使用基类指针引用派生类成员
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 存储模板类型以强制转换回派生<T>
- 需要从 istream 和 ostream 派生 iostream
- 在 C++ 中用派生类型重写成员函数
- 具有多个类、派生类的C++正向声明
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 如果基类包含双指针成员,则派生类的构造函数
- 为什么此派生对象无法访问基类的后递减方法?
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践