Template

I am writing a function template which returns the total of the values that we input. The function template should receive a number as an argument which indicates the number of values will be input.

This is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
template <class T>
T total(T size)
{
	T total = 0;
	T temp;

	for (T count = 0; count < size; count ++)
	{
		cin >> temp;
		cin.ignore();

		total += temp;
	};

	return total;
};


int main()
{

	cout << total(2);

	return 0;
}



When I want to input int values, I just pass an int value as an argument. When I want to input double values, I just pass a double value as an argument (Eg: 2.0).
Is this the best way to let the function know which data type will be input? Or is there a more efficent way to do it?
I will say that it is probably the EASIEST way to do it. Another way is to simply write out different constructors for a class per data type, or write out different stand-alone functions per data type.

e.g.

total (float);
total (int);
total (double);

But now that I think about it...C++ uses implicit type conversion anyway, so you could probably write 1 void function that uses the cout function within it (without having to actually return a specific data type), and it will give you output in the same format you put in. But it would have to be the worst case scenario data type so it would not truncate (going from a longer to shorter data type, e.g. from a double to a float).
Probably the most robust and correct way to do so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template<
    typename T, //Type we want to sum. It can be anything from int to std::string, to some custom type
>
T total(std::size_t size) //Size passed as parameter
{
  //... 
}

//Usage

//You cannot do that with original code
//Also it shows clearly what is original type is.
auto x = total<unsigned char>(400);

auto y = total<std::string>(2); //Works just fine 

Topic archived. No new replies allowed.