Adding C++ templates causing an error on a blank line

Hi, I'm currently working on a project and I want to use the C++ template for a function because I need the function to be able to use both int and string. However, when I compiled the code, it shows an error that I think looks like shouldn't be there because the error message told me there's something wrong in a line that is all comments.

Here is the function:

void clearDisplay(){
  digitalWrite(D1, LOW);
  digitalWrite(D2, LOW);
  digitalWrite(D3, LOW);
  digitalWrite(D4, LOW);
}

//Error here
template <typename T>
void blinkDisplay(int blinkDelay, void (*function)(T), T arg){
  static bool first = true;
  static unsigned long initTime;
  if(first){
    initTime = millis();
  }
  if(millis() - initTime >= blinkDelay){
    clearDisplay();
    first = true;
    delay(blinkDelay);
  }
  else{
    function(arg);
    first = false;
    blinkDisplay(blinkDelay, function, arg);
  }
}
blinkDisplay<String>(250, &show, "FAIL");
blinkDisplay<int>(500, &show, counter);

And here is the error message:

Arduino: 1.8.15 (Windows 10), Board: "Arduino Uno"





















Reaction_Test:69:75: error: expected ')' before ';' token

 //Error here

                                                                           ^

exit status 1

expected ')' before ';' token



This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Does anyone know what is causing the problem? I'm a bit frustrated by this.

Please post a complete sketch that illustrates the problem and the full error message that goes with it copied using the "Copy error message" button in the IDE

in the temporary build folder check the .ino.cpp file

This is a bug in the Arduino preprocessor. A quick but ugly workaround is to write the template <...> on the same line as the return type:

template <typename T> void blinkDisplay(...) {

I usually get around this bug by moving most (template) functions into a separate .hpp file (as a “tab” in the IDE) and then #including that file in my sketch (or just leaving the .ino file empty in the first place, and just doing everything in a .cpp file).

1 Like

Hi Pieter, thanks for the suggestion. Can you please elaborate on this workaround? I'm still a beginner :frowning:

Add a tab in the IDE, using the down arrow button in the top right, or using the CTRL+Shift+N shortcut:


Enter a name and add the file by clicking “OK”.

The contents of the files could be, for example:

sketch.ino

#include "PrintAnything.hpp"

void setup() {
  Serial.begin(115200);
  while (!Serial);
  printAnything("Hello, world!");
  printAnything(42);
}

void loop() {}

PrintAnything.hpp

#pragma once

#include <Arduino.h>

template <class T>
void printAnything(const T &t) {
  Serial.println(t);
}

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.