C++/Generic/Template Overload
A generic version of myabs().
#include <iostream>
using namespace std;
template <class X> X myabs(X val)
{
return val < 0 ? -val : val;
}
int main()
{
cout << myabs(-10) << "\n"; // integer abs
cout << myabs(-10.0) << "\n"; // double abs
cout << myabs(-10L) << "\n"; // long abs
cout << myabs(-10.0F) << "\n"; // float abs
return 0;
}
Define template function for class type
#include <iostream>
using namespace std;
template <class type1, class type2>
void myFunction(type1 x, type2 y)
{
cout << x << " " << y << "\n";
}
int main()
{
myFunction(10, "hi");
myFunction(0.23, 10L);
return 0;
}
Overload a function template declaration.
#include <iostream>
using namespace std;
template <class X> void f(X a)
{
cout << "Inside f(X a)\n";
}
template <class X, class Y> void f(X a, Y b)
{
cout << "Inside f(X a, Y b)\n";
}
int main()
{
f(10);
f(10, 20);
return 0;
}