11.1.1.  Function Templates

[ fromfile: templates.xml id: functiontemplates ]

Example 11.1. src/templates/template-demo.cpp

[ . . . . ]

template <class T> T power (T a, int exp) {
  T ans = a;
  while (--exp > 0) {
    ans *= a;
  }
  return (ans);
}

Example 11.2. src/templates/template-demo.cpp

[ . . . . ]


int main() {
  Complex z(3,4), z1;
  Fraction f(5,6), f1;
  int n(19);
  z1 = power(z,3);              1
  f1 = power(f,4);              2
  z1 = power<Complex>(n, 4);    3
  z1 = power(n,5);              4

}

1

First instantiation: T is Complex.

2

Second instantiation: T is Fraction.

3

Supply an explicit template parameter if the actual argument is not "specific" enough. This results in a call to a function that was already instantiated.

4

Which version gets called?


[Note]Note

One important difference between overloaded functions and multiple specializations of the same template function is that overloaded functions must return the same type. Example 11.2 shows different versions of the template power() function with different return types. Overloaded functions must all have the same return type.