Fork me on GitHub

Project Notes

#486 UsingTemplates

Learning how to use C++ template functions in embedded projects with an Arduino.



LuckyResistor has just published C++ Templates For Embedded Code, the first in a series on the subject of C++ templates.

This is great! Although I’ve dabbled in C++ for years, I’ve never fully taken templates on board. Proving that they can be beneficial for embedded development is a bonus.

The First Example - circularShift

I’ve taken the circularShift example from the article, and extended the code a little to toggle the LED on pin 13 everytime circularShift wraps a 1 around.

One important point to note if you are copying code from the article:

The declaration and implementation of a function template have to be in a header file

With Arduino IDE 1.8.2, I get a compiler error like this if I try and put templates in the main sketch file:

UsingTemplates:12: error: variable or field 'circularShift' declared void
 void circularShift(Value &value) {
UsingTemplates:12: error: 'Value' was not declared in this scope
UsingTemplates:12: error: 'value' was not declared in this scope
 void circularShift(Value &value) {
exit status 1
variable or field 'circularShift' declared void

Putting the template in a header file fixes this. Also, Arduino IDE 1.8.9 does not have this issue - it can compile templates in the sketch file.

Test Run

From the console, the first iterations checkout - correct right shift on both values (should improve this to include leading 0s in the output)







Credits and References

Project Source on GitHub Project Gallery Return to the LEAP Catalog

This page is a web-friendly rendering of my project notes shared in the LEAP GitHub repository.

LEAP is just my personal collection of projects. Two main themes have emerged in recent years, sometimes combined:

  • electronics - usually involving an Arduino or other microprocessor in one way or another. Some are full-blown projects, while many are trivial breadboard experiments, intended to learn and explore something interesting
  • scale modelling - I caught the bug after deciding to build a Harrier during covid to demonstrate an electronic jet engine simulation. Let the fun begin..
To be honest, I haven't quite figured out if these two interests belong in the same GitHub repo or not. But for now - they are all here!

Projects are often inspired by things found wild on the net, or ideas from the many great electronics and scale modelling podcasts and YouTube channels. Feel free to borrow liberally, and if you spot any issues do let me know (or send a PR!). See the individual projects for credits where due.