generic function how to set up declaration,prototype

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi I am trying to learn how to set up and use generic functions (can operate on different data types). I have a simple function to add any type, set up a
//template function to add any 2 types togethe
template<class T
T Addition(T first,T second

T tempvar
tempvar=first + second
return (tempvar)


I am trying to use it by adding 2 float types
double rsum
rsum = Addition(2.2,3.3);//call generic function, but get error C3861, Addition adentifier not found. I do not have
delcaration yet so think this is the problem. What would be the proper declaration-or prototype if I want this as a global function, ie not part of a class? Thanks Paul.
 
I got it working by moving the generic function under just above main. Looks like you do not need a declaration since type is unknown.
 
Paul said:
Hi I am trying to learn how to set up and use generic functions
(can operate on different data types). I have a simple function
to add any type, set up as //template function to add any 2 types
together
template<class T>
T Addition(T first,T second)
{
T tempvar;
tempvar=first + second;
return (tempvar);
}

I am trying to use it by adding 2 float types,
double rsum;
rsum = Addition(2.2,3.3);//call generic function, but get error
C3861, Addition adentifier not found. I do not have a
delcaration yet so think this is the problem. What would be the
proper declaration-or prototype if I want this as a global
function, ie not part of a class? Thanks Paul.

Hi Paul,

this compiles for me:

template<class T>
T Addition(T first,T second)
{
T tempvar;
tempvar=first + second;
return (tempvar);
}

int main()
{
double rsum = Addition(2.2,3.3);
return 0;
}

HTH,

Schobi

--
(e-mail address removed) is never read
I'm Schobi at suespammers dot org

"Sometimes compilers are so much more reasonable than people."
Scott Meyers
 
Paul said:
Hendrick,
yep seems to be working now, thanks for the reply.
I had the generic function below the main {} at first
and this caused a compiler error.

FWIW, if it's all in one file, this

template<class T>
T Addition(T first,T second);

int main()
{
double rsum = Addition(2.2,3.3);
return 0;
}

template<class T>
T Addition(T first,T second)
{
T tempvar;
tempvar=first + second;
return (tempvar);
}

compiles and links for me as well.
However, I don't think this is std
conforming.

Schobi

--
(e-mail address removed) is never read
I'm Schobi at suespammers dot org

"Sometimes compilers are so much more reasonable than people."
Scott Meyers
 
Back
Top