Welcome to Dream.In.Code
Become a C++ Expert!

Join 137,183 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,392 people online right now. Registration is fast and FREE... Join Now!




Help with a template function

 
Reply to this topicStart new topic

Help with a template function

faisaly
8 Jul, 2008 - 08:15 PM
Post #1

New D.I.C Head
*

Joined: 28 May, 2007
Posts: 13


My Contributions
Dear All,

Kindly help me regarding this question.

Write a template function that returns the average of all the elements of an array. The
arguments to the function should be the array name and the size of the array (type int). In
main(), exercise the function with arrays of type int, long, double, and char.

User is offlineProfile CardPM
+Quote Post

gabehabe
RE: Help With A Template Function
9 Jul, 2008 - 03:37 AM
Post #2

Donkey DIC
Group Icon

Joined: 6 Feb, 2008
Posts: 5,556



Thanked: 99 times
Dream Kudos: 2650
Expert In: ruling the world.

My Contributions
Dream.In.Code has a policy by which we prefer to see a good faith effort on your part before providing source code for homework assignments. Please post the code you have written in an effort to resolve the problem, and our members would be happy to provide some guidance. Be sure to include a description of any errors you are encountering as well.

Please post like this:

Thank you for helping us helping you.
User is online!Profile CardPM
+Quote Post

polymath
RE: Help With A Template Function
9 Jul, 2008 - 08:52 AM
Post #3

D.I.C Regular
Group Icon

Joined: 4 Apr, 2008
Posts: 415



Thanked: 4 times
Dream Kudos: 500
My Contributions
Templates look like this:

cpp

template <class T>
T templated_function (T varA, T varB ) {
//CODE
}


To call a template (Example):

cpp

#include <iostream>
using namespace std;

template <class T> //you can replace "T" with what you like...
T add (T a, T B ) { //The reason we need a template here is because you
T returnVal=a+b; //can add ints and floats, and its much easier to use a
return (T); //than making a int add and a float add function, since
} //adding floats is a float and adding ints is an int, so you
//need different return types
int main() {
int a=1;
int b=2;
float x=1.2;
float y=3.4;
cout << add <int> (a,b ) << endl;
cout << add <float> (x,y) << endl;
cin.get();
return 0;
}


for more, go to: http://www.cplusplus.com/doc/tutorial/templates.html

hope this helps smile.gif

This post has been edited by polymath: 9 Jul, 2008 - 08:53 AM
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/4/08 11:22AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month