cannot write template functions

The solution is probably stupid, though I cant manage to find where it buggs.

This code works

template <class T> class test
{
	public: T t;
	test(T n) : t(n) { Serial.println(t) ; };
};

void setup() 
{
  Serial.begin(9600);
  test<int>(5) ;
}

void loop(){}

but this one does not

template <class T> void test(T t)
{
	Serial.println(t) ;
}

void setup() 
{
  Serial.begin(9600);
  test<int>(5) ;
}

void loop(){}

The error is:

SandBox.ino:2:11: error: variable or field 'test' declared void
SandBox.ino:2:11: error: 'T' was not declared in this scope

Thanks for helping.

I to sound like a broken record, but this is another case of the IDE trying tobe helpful and rearranging your code. Templates are best kept in .h files and included instead.

You can write the whole program, including loop and setup functions, using .h and .cpp files like you would a normal C++ program. You just need a .ino file with all the #includes in it to make the IDE compile for you. That may help make things a little more familiar to you and stop some of the seemingly senseless errors.

The arduino IDE allow you to have multiple tabs, and with this you can have a .h tab.

Make a new tab and call it myTemplates.h, then save it.

template <class T> void test(T t)
{
  Serial.println(t) ;
}

Main tab

#include "myTemplates.h";

void setup() 
{
  Serial.begin(9600);
  test<int>(5) ;
}

void loop(){}

To make a new tab, locate the Serial monitor button in the top right corner, and under that should be a down arrow. Or simply press CTRL + SHIFT + N.

Thanks again! This is the second time I got trapped by the fancy behavior of the IDE. why hell did they do that this way!

BTW, I do not use the IDE anymore for editing. I use Notepad++ instead.

I use Notepad++ to create/write my libraries but I was never able to get the code to compile from Notepad++. :confused:

Babylone: ... BTW, I do not use the IDE anymore for editing. I use Notepad++ instead.

@HazardsMind: :smiling_imp: Reading posts in diagonal is "bad" ;)

HazardsMind: I use Notepad++ to create/write my libraries but I was never able to get the code to compile from Notepad++. :confused:

I did too until I realized that you have to save everything BEFORE you hit the compile button or it compiles the last saved version.

I'm using Eclipse now with the Arduino plugin. I like it a lot better than the IDE, but I hear the newest versions don't play well with Windows.