• Advertisement
Sign in to follow this  

using multiple data types with c++

This topic is 4429 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hi, i'm trying to make a function that does operations with numbers. for example it does this: a = c + b; but i want it to be able to do the operation with int, float, double, long and other number types at once; so it means that i could pass a float or integer to a same function. is it posible in c++ to pass a parameter to a function that won't care variable type like this?

Share this post


Link to post
Share on other sites
Advertisement
You can use templates:


template <typename T>
T myfunc(T a, T b)
{
return a + b;
}


Also the boost library provides a variant data type. Maybe this is what you are looking for.

Share this post


Link to post
Share on other sites
Use operator overloading.

e.g.


myNumberClass operator+(myNumberClass c, int i)
{
//whatever
}


myNumberClass operator+(myNumberClass c, float f)
{
//whatever
}


myNumberClass operator+(myNumberClass c, double i)
{
//whatever
}


Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement