Function with multiple datatypes

Can someone explain to me how I can create a function that returns a value based on a datatype.

For example:
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
// this function returns int
int SquareInt ( int x )
{
  return x * x;
}

// this function returns float
float SquareFloat ( float x )
{
  return x * x;
}

// For example, if I wanted to consolidate
// these two functions into one, how would
// I go about doing this?

some_dataype Square ( some_dataype x )
{
   return x * x;
}


// then I can do something like
float a = Square (some_float_var);
int b = Square (some_int_var);


Any help is appreciated. Thanks! :)
This will help you figure out how to make a function that can do the exact same thing to whatever data type happens to be passed to it.

http://www.cplusplus.com/doc/tutorial/templates/
I believe basic template stuff would be enough for this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

template <class T>
T Square(T x) { return x*x; }

int main()
{
    int n=Square(2);
    double f=Square(2.5);

    cout << n << endl;
    cout << f << endl;

    cout << "\n(hit enter to quit...)";
    cin.get();

    return 0;
}

Useful link -> http://www.cplusplus.com/doc/tutorial/templates/

EDIT: Oh, too slow... -.-
Last edited on
Hey, thanks a lot guys! :D
Topic archived. No new replies allowed.