I'm trying to learn templates. :~ I've been reading a tutorial (Web page: An Idiot's Guide to C++ Templates - Part 1 - CodeProject ). I copied an example from the tutorial but when I compile I get an error: 'TYPE' does not name a type, it highlights the error line as the first line, the line declaring the template.
Here's my sketch:
template<class TYPE>
TYPE Add(TYPE n1, TYPE n2)
{
TYPE result;
result = n1 + n2;
return result;
}
void setup()
{
float x = 2.1;
float y = 5.6;
Serial.begin(115200);
Serial.println(Add(x, y));
}
void loop()
{
}
I thought the purpose of using a template (in this case) was so you didn't have to (explicitly) name a type. Can someone help me understand why I'm getting an error and the author of the tutorial (obviously) is not.
I did figure out it was the IDE when it compiled using atmel studio. I had no idea how to get it to compile in the arduino IDE. I'll give this a try and let you know if it works for me.
template<class TYPE> TYPE Add(TYPE n1, TYPE n2);
TYPE Add(TYPE n1, TYPE n2)
{
TYPE result;
result = n1 + n2;
return result;
}
void setup()
{
float x = 2.1;
float y = 5.6;
Serial.begin(115200);
Serial.println(Add(x, y));
}
void loop()
{
}
The error is at line 3. I was mistaken in my first post. The error was in the same place as indicated this time. I'm using a Mega1280 & IDE1.0.2. Any further thoughts/ideas. As I stated above I can get this to compile using atmel studio. It's just easier to do short code tests using the arduino IDE.
template<class TYPE> TYPE Add(TYPE n1, TYPE n2);
TYPE Add(TYPE n1, TYPE n2)
{
TYPE result;
result = n1 + n2;
return result;
}
Yes, but the function above does not match the prototype.
This compiles under IDE 1.0.2:
template<typename TYPE> TYPE Add(TYPE n1, TYPE n2);
template<typename TYPE> TYPE Add(TYPE n1, TYPE n2)
{
TYPE result;
result = n1 + n2;
return result;
}
It won't compile under 1.0.1 because that doesn't honour function prototypes when the IDE tries to generate its own.
@WizenedEE
You forgot Serial.begin();
To be honest I have no idea how your example works. :~ I'm not that good at coding yet. But thanks for it anyway. I'll study it some more and see if I can figure it out.