Go Down

Topic: Help using templates. (Read 716 times) previous topic - next topic

DigitalJohnson

Nov 26, 2012, 12:53 pm Last Edit: Nov 26, 2012, 02:21 pm by DigitalJohnson Reason: 1
I'm trying to learn templates. :~ I've been reading a tutorial (Web page: http://www.codeproject.com/Articles/257589/An-Idiots-Guide-to-Cplusplus-Templates-Part-1 ). 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:
Code: [Select]

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.

Thanks for your time,
DJ
DigitalJohnson

pYro_65

This is the IDE's fault, add the function prototype above the definition:

Code: [Select]
template<class TYPE> TYPE Add(TYPE n1, TYPE n2);

The IDE otherwise generates a prototype as:

Code: [Select]
TYPE Add(TYPE n1, TYPE n2);

leaving TYPE as undefined.

DigitalJohnson

@pYro_65

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. ;)

Thanks,
DJ
DigitalJohnson

DigitalJohnson

Nope. Same error: 'TYPE' does not name a type.

My sketch:
Code: [Select]

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.

Thanks again for any help,
DJ
DigitalJohnson

PaulS

You may need to put your template function declaration in a separate header file, and include it in the sketch.

By the time you get to templates, this should be second nature.

Go Up