What's the benefit of using a class template parameter over using an instance variable?

arduino, c++, coding-style, templates

Solution

"Is there an advantage using the first class over the second or is this just a matter of taste? :)"

Yes. In the template case, compiler can use the numeric value directly without need to store the variable saving both memory (the number would have to be stored in RAM in the non-template case) and power (you would need instruction which saves the byte to the memory, then load to a register instead of loading to the register directly).

Both saving are so small in case of normal PC that it really doesn't matter, but in case of small devices (like microcontroller) with low RAM (~ under 1MB) and slow CPU each and every byte matters.

However, if you use the template for more pins (with different numbers), your application will contain multiple methods for turning it on and off (for each used pin number) increasing size of the executable. In that case you're saving memory for data and CPU power in expense of memory for application and then it depends what you need more - smaller application with bigger memory and CPU power expenses, or vice-versa.

Problem

When getting in touch with microcontroller programming (Arduino), I saw the following class to control an 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 via ``` LED<8> led; led.turnOn(); ``` to light an LED on Pin 8. But I ask myself: Why is the pin given as a template parameter, why not as an instance attribute? What's the benefit of the first class over this one? ``` 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 like this: ``` LED led(8); led.turnOn(); ``` Is there an advantage using the first class over the second or is this just a matter of taste? :)

Original source