Doubt regarding functions with <> and () statements

Hi everyone.

First of all thanks all for your help. I'm trying to program some more advanced stuff with arduino, and I'm having troubles to find out how does it works a function that it's declared as follow:

void functionname<x, y>(a, b){}

In specific I don't understand the part that it's between the "< >". What is the "< >" part for?

I tried to search in this and in other forums about this, but I wasn't able to find it out.

I really appreciate for your help.

Regards,

That is a template. Between the '<' and '>' is the type. The type can be an integer or a float but also a Class. The compiler will solve that during compiling.

When the same function should be used with a number of different variable types, they all can be defined in a Class. That is called overloading.

A template is much more flexible than overloading. A Class with a template can use an other Class without knowing which Class that will be. The compiler will solve that during compiling.

In old 'C' that would require pointers to functions and pointers to data. Everything is fixed and all the types must be known and must match. The 'C++' template is much more powerful.

Function overloading and templates: http://www.cplusplus.com/doc/tutorial/functions2/

Class overloading and templates: http://www.cplusplus.com/doc/tutorial/templates/

Thank you so much Koepel.

I'll review then the links and study a little more about templates.

Thanks again.

It should be noted that the values between the angled brackets don't necessarily have to be class names, they can also be (static) values, like integers. You can even have a variable number of parameters (see variadic function templates).

A common use is a template function that works with different sizes of arrays.
In the following examples, a template is used to print the elements of an array, there are two template parameters: one for the type of elements in the array, and one for the length of the array.

Code:

---



```
template <class T, size_t N> size_t printArrayTo(Stream &s, T color=#000000[/color][N])
size_t printed = 0;
for (T &element : array)
printed += s.printcolor=#000000[/color] + s.print(' ');
return printed;
}

void setupcolor=#000000[/color] {
 Serial.begincolor=#000000[/color];
 whilecolor=#000000[/color];
 
 int numbers[] = { 1, 2, 3, 4, 5, 6 };
 const char* strings[] = {"Hello,", "World!"};

printArrayTo(Serial, numbers);
 Serial.printlncolor=#000000[/color];
 printArrayTo(Serial, strings);
 Serial.printlncolor=#000000[/color];
}

void loopcolor=#000000[/color] {}
```

|

Output:

---



```
1 2 3 4 5 6
Hello, World!
```

Pieter