So why doesn't this work ?
the .h file
template <class T>
void printBinA(T data);
the .cpp file
#include <Arduino.h>
#include "PrintBin.h"
void printBinA(T data)
{
for (int b = (sizeof(data) * 8) - 1; b >= 0; b--)
{
if ((data & (1 << b)))
{
Serial.print(1);
}
else
{
Serial.print(0);
}
}
}
the test sketch
#include "PrintBin.h"
void setup()
{
Serial.begin(115200);
int var = 0b0101010110101010;
printBinA(var);
}
void loop()
{
}
the error message
Arduino: 1.8.13 (Windows 10), Board: "Arduino Nano, ATmega328P"
PrintBin.cpp:4:16: error: variable or field 'printBinA' declared void
void printBinA(T data)
^
PrintBin.cpp:4:16: error: 'T' was not declared in this scope
exit status 1
variable or field 'printBinA' declared void
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
Ok, but I am trying to keep this simple and not have the need to create an instance of an object to use the PrintBin functions. If I simply put the template function in the .h file, like this
template <class T>
void printBinA(T data)
{
for (int b = (sizeof(data) * 8) - 1; b >= 0; b--)
{
if ((data & (1 << b)))
{
Serial.print(1);
}
else
{
Serial.print(0);
}
}
}
and remove the .cpp file I can call the function perfectly well just like a non template function, but with any integer data type. However, I have seen advice previously that this is bad practice and should not be done, so I was trying to do it the correct way