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

About LEAP#486 ArduinoC++
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 my personal collection of electronics projects, 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 (IMHO!).

The projects are usually inspired by things found wild on the net, or ideas from the sources such as:

Feel free to borrow liberally, and if you spot any issues do let me know. See the individual projects for credits where due. There are even now a few projects contributed by others - send your own over in a pull request if you would also like to add to this collection.