Question Details

No question body available.

Tags

object-oriented c++ software

Answers (1)

March 17, 2025 Score: 4 Rep: 4,896 Quality: Medium Completeness: 80%

TLDR

const std::vector& getLeds() const;
const std::vector& getSensors() const;
const std::vector& getGpios() const;

Exposing internal data structure is a bit yucky, so consider alternatives

Rationale

A homogeneous storage for heterogeneous items is optional. A false commonality is detrimental. Predetermined peripheral types can be queried independently.

Example

Warning: this example has sliced away the polymorphism of peripherals. Replace all periphery instances with uniqueptr and add virtual methods for polymorphic behavior.

#include 
#include 
#include 

class Led { public: explicit Led(const std::string& name) : name(name) {}

private: std::string name; };

class Sensor { public: explicit Sensor(const std::string& type) : type(type) {}

private: std::string type; };

class Gpio { public: explicit Gpio(int pin) : pin(pin) {}

private: int pin; };

class Board { protected: // Adders are just for illustration. A board can populate or store the periphery however they like, it will have to use virtual dispatch then, though. void addLed(const Led& led) { ledList.push
back(led); }

void addSensor(const Sensor& sensor) { sensorList.pushback(sensor); }

void addGpio(const Gpio& gpio) { gpioList.push
back(gpio); }

public: // No need for unnecessary abstraction and "inidicator" interfaces. const std::vector& getLeds() const { return ledList; } // Do not coerce different type into a single one. const std::vector& getSensors() const { return sensorList; } // Use a dedicated accessor for every type const std::vector& getGpios() const { return gpioList; }

virtual ~Board() {}

private: std::vector ledList; std::vector sensorList; std::vector gpioList; };

class MyBoard : public Board { public: MyBoard() { addLed(Led("Red")); addLed(Led("Green")); addSensor(Sensor("Temperature")); addSensor(Sensor("Humidity")); addGpio(Gpio(17)); addGpio(Gpio(22)); } };

int main() { MyBoard container;

std::cout