You can make use of CRTP. Add a templated second base class to hold the ID handling code.
template <class T>
class ComponentID {
public:
ComponentID(std::string &id_) {
// Same as updateID above
}
};
class Wire: public Component, ComponentID<Wire> {
public:
Wire(const std::string& name = "Wire") : Component(name), ComponentID(id_) {
}
// ...
};
template<size_t BusSize>
class Bus : public Component, ComponentID<Bus<BusSize>> {
public:
explicit Bus(const std::string& name = "Bus") : Component(name), ComponentID(id_) {
createBus();
}
// ...
};
We’re passing in the id_
field from the Component
base class to the ComponentID
constructor so that it can be updated without having to change the access to id
.
5
solved What can I do to remove or minimize this code duplication that will provide the same functionality and behavior?