【发布时间】:2019-02-18 02:21:56
【问题描述】:
考虑以下类定义:
class Car : public Vehicle {
private:
TouchScreen a;
RadioAntenna b;
Blah c;
public:
Car(TouchScreen &a1) {
a = a1; //copy ctor
}
Car(RadioAntenna &b1) {
b = b1;
}
Car(Blah &c1) {
c = c1;
}
void update(Touchscreen &a1) {
a.update(a1);
}
void update(RadioAntenna &b1) {
b.update(b1);
}
void update(Blah &c1) {
c.update(c1);
}
}
class Fleet {
private:
std::map<int, Car> _fleet; //vehicle number, Car
public:
template <typename T>
void update(int vehicle_num, T &t) {
auto it = _fleet.find(vehicle_num);
if (it == _fleet.end()) {
_fleet[vehicle_num] = Car(t);
}
else {
it->second.update(t);
}
}
}
Fleet 包含汽车的集合。如果要更新特定汽车的成员变量,
Fleet f;
f.update<TouchScreen>(4, a1);
f.update<Blah>(10, c1);
未来,可以在 Car 内部定义更多的类实例。有没有办法减少重载的 Constructor 和 update() 函数的数量?也许使用模板?我觉得它看起来丑陋,设计明智,使用了这么多重载函数。
【问题讨论】:
标签: c++ templates polymorphism overloading