Duck-typing using C++ class templates

I ran into a code conundrum while writing last week's 7-segment LED display article. I wrote the code for an Arduino, but don't want it to be stuck there. Very little code is Arduino specific and there are lots of fun platforms out there. Breaking the display driver from the chip IO would be a good start. On the desktop I'd create an abstract base class describing the needed IO methods, then implement just that for each new platform.

Abstract Base Classes

class LedIO {
        virtual void led_off() = 0;
        virtual void led_on() = 0;

class  ArduinoIO : public LedIO {
        ArduinoIO(int led_pin) : led_pin{led_pin} {
            pinMode(led_pin, OUTPUT);
        void led_off() override {
            digitalWrite(latch_pin, LOW);
        void led_on() override {
            digitalWrite(latch_pin, HIGH);

But... Aren't virtual functions too expensive to use on a little 8-bit embedded platform?

Published 25 Sept. 2021