Electronic – arduino – What’s wrong with the C++ Template code for Arduino

arduinoc

I'm trying to implement a C++ templated member function in Arduino 0022, but I'm getting an error in code which seems correct to me.

// in Settings.h
template <class T> void save( T variable );

// in Settings.cpp
template <class T> void Settings::save( T variable ) {
  Serial.println("Want to save a variable of size " + String( sizeof(T) ) );
};

// compiler (linker) output
TimeMachineArduino.cpp.o: In function SimpleScreen::left():

SimpleScreen.h:85: undefined reference to void Settings::save<int>(int)

SimpleScreen.h:86: undefined reference to void Settings::save<double>(double)

SimpleScreen.h:87: undefined reference to void Settings::save<char>(char)

The SimpleScreen::left() function is where I'm implicitly instantiating the template functions (by calling save on an int, double, and char).

Best Answer

You need to move the contents of the .cpp file into the .h file. Separating declarations and definitions doesn't work for templates. See the link @sharptooth posted: https://stackoverflow.com/q/648900.