I got a problem that is not for homework in the book. It states...

"Total Template
Write a template for a function called total. The function should keep a running
total of values entered by the user, then return the total. The argument sent into the
function should be the number of values the function is to read. Test the template in a
simple driver program that sends values of various types as arguments and displays
the results.
(Starting Out with C++: From Control Structures through Objects, 6th Edition. Addison-Wesley/CourseSmart, 03/19/2008. 1024)

Here is my code...

#include <iostream>
using namespace std;

template <class T>
T total(int number)
	T total = 0, aNumber;
	for(int count = 0; count < number; count++)
		cin >> aNumber;
		total += aNumber;
	return total;

int main()
	double totalNum;
	int aNumber;

	cout << "Enter how many numbers you wish to add up: " << endl;
	cin >> aNumber;
	totalNum = total(aNumber);

	cout << "The total is " << totalNum;

	return 0;


My question is, if i want the loop to run X amount of times as a paremeter given into the total function, why would i leave that open to anything other than an Int. Could i literally run a loop inside the function a double like 6.7 amount of times? I don't think so, it makes more sense to me that the problem is faulty and i should make a template to add up a various list of numbers that could be anything into a total and return it. So is that not possible or am i not getting the problem.

StuXYZ commented: Intelligent question, thx. +5

Recommended Answers

All 2 Replies

I am not sure the problem is actually faulty, but you have figured out templates so the problem is far too simplistic. The problem seems to be based on the type of return and the problem that you have to specify the return type. i.e. your code does not compile since you have to write totalNum = total<int>(aNumber); However, considering your last question.
You can readily make a template that takes an array (size set at compile time, and adds the array up.

template<Stuff for you to figure out>
int total( More stuff for you to write )  // defines variable X
   int total(0);
   for(int i=0;i<size;i++)   // size is a template parameter.
   return total;

int main()
   int A[]={1,2,3,4};
   int B[]={9,8,7,6,5,4,3,2,1};
   std::cout<<"Total == "<<total(A)<<std::endl;  // : 10
   std::cout<<"Total == "<<total(B)<<std::endl;  // : 45 


I think that is the question you are asking. The answer is that you can do that. Have a think about it and let us know how you get on.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.