Store 2 integers in a template

Can I use template<> to store 2 integer? Something like template<int, int>
If yes, how?
For what purpose?

The template syntax describes how to autogenerate a type definition.
Type definition describes properties for objects.
Objects hold values.
Nevermind. I just want to know when to use template (with examples)
Last edited on
if you want to store pair of integers, or that matter group any data type you use tuples
http://www.cplusplus.com/reference/tuple/

For usage of templates and examples http://www.cplusplus.com/doc/oldtutorial/templates/
OK, I'll give an example for function templates. If u need a function that has similar code(i.e., the body of the function is more or less similar) for many types.

Best and simplest example that comes to my mind is the add(object1, object2) function. If you need the add() function for adding integers, floats, doubles, etc., then use function templates instead of function overloading.

Instead of...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int add(int a, int b)
{
 return a + b;
}

float add(float a, float b)
{
 return a + b;
}

double add(double a, double b)
{
 return a + b;
}


It is better to use...
1
2
3
4
5
template <typename T>
T add(T a, T b)
{
 return a + b;
}


However, be cautious that templates can't be applied genereically to each and every function out there.

Use function templates only in places where the code remains same and only data types differ. Use overloading if you need to perform different actions in each version of the function with different data types.

Coming to your original post, it looks like you want to create a data type which has two integers as it members?
Last edited on
Look at the C++ Standard Library. It is mostly template code.

For example the std::vector. Vector is a container that stores values in certain way and offers certain routines. The only thing that differs, is the type of the values. The library doesn't have a vector of integers, vector of doubles, vector of strings, and it certainly could not have a vector of that class type that you have not even written yet. The library does have a template of a vector so that when you do need a vector of integers, the compiler can generate it for you.

Function templates. Function overloading. See std::max
template <class T> const T& max (const T& a, const T& b);
Every max returns the larger of the two parameters.
Every max has same behaviour independent of the type of the parameter.
You could write a concrete overload of max() for every type that you know.
Template saves you from such copy-paste and provides overloads for future types too.
Topic archived. No new replies allowed.