- #36
Mark44
Mentor
- 37,735
- 10,073
@yungman, inasmuch as there was some discussion in this thread about overloading, I though I would throw in an example that is somewhat in the same vein, in which multiple versions of two functions are created at compile time.
This is really about template functions, a topic you probably haven't seen yet.
Output:
In the last line, the sum is 8.5 + 1i, and the product is 21 + 13i, the usual notation for complex numbers that mathematicians use.
This is really about template functions, a topic you probably haven't seen yet.
C++:
// TemplateFn.cpp - Example of a templatized function
#include <ccomplex>
#include <iostream>
using std::complex;
using std::cout;
using std::endl;
template <class T> // Template function for sum
T sum(T a, T b) { return a + b; }
template <class T> // Template function for product
T prod(T a, T b) { return a * b; }int main()
{
// Create three instances of each template function
int a = 3, b = 5;
// Call sum() and prod() with int arguments
int intRet1 = sum<int>(a, b);
int intRet2 = prod<int>(a, b);
cout << "Integer sum: " << intRet1 << " product: " << intRet2 << endl;
double c = 2.5, d = 3.8;
// Call sum() and prod() with double arguments
double dblRet1 = sum<double>(c, d);
double dblRet2 = prod<double>(c, d);
cout << "Double sum: " << dblRet1 << " product: " << dblRet2 << endl;
complex<double> e = { 2.5, 3.0 }, f = { 6.0, -2.0 };
// Call sum() and prod() with complex arguments
complex<double> cmplxRet1 = sum<complex<double>>(e, f);
complex<double> cmplxRet2 = prod<complex<double>>(e, f);
cout << "Complex sum: " << cmplxRet1 << " product: " << cmplxRet2 << endl;
}
Output:
Code:
Integer sum: 8 product: 15
Double sum: 6.3 product: 9.5
Complex sum: (8.5,1) product: (21,13)