When I came into contact with the programming of the microcontroller (Arduino), I saw the following class for controlling the LED on a specific pin:
template <const uint8_t PIN> class LED { public: LED() { pinMode(PIN, OUTPUT); } void turnOn() { digitalWrite(PIN, HIGH); } void turnOff() { digitalWrite(PIN, LOW); } };
I can use it through
LED<8> led; led.turnOn();
so that the LED on pin 8 lights up.
But I ask myself: Why is the contact specified as a template parameter, why not as an instance attribute? What is the use of first class over this?
class LED { public: LED(uint8_t ledPin) : pin(ledPin) { pinMode(pin, OUTPUT); } void turnOn() { digitalWrite(pin, HIGH); } void turnOff() { digitalWrite(pin, LOW); } private: uint8_t pin; };
and use it as follows:
LED led(8); led.turnOn();
Is there an advantage to using the first class over the second or is it just a matter of taste? :)
c ++ coding-style templates arduino
user3690739
source share