5 inline template functions vs. macros

To make your life easier, you can define the following parametrized macro:

#define MYMAX(x,y) (x < y)?y:x

Recall that a macro is expanded before compilation. There is no type checking when a macro expands. This means that we can do the following:

int x, y, z;
float p, q, r;

// ...
p = MYMAX(q,r);
x = MYMAX(y,z);

This is better than having to define a max function for int, then another one for float. However, macro expansion does not take syntax into consideration. This means it can lead to obscure problems later on. Functions, on the other hand, are parsed and analyzed by the compiler, which helps to prevent problems due to badly formed syntax.

In C++ (but not in C), you can use an inline template function in place of macros. In our example, we can use the following:

inline template <class X> X mymax(X a, X b)
{
  return (a < b)?b:a;
}

In this definition, the type of a and a is parametrized as X. Although the definition of a function template is kind of complex and ugly, using (``calling'') one is not:

int x, y, z;
float p, q, r;

// ...
p = mymax(q,r);
x = mymax(y,z);

Note that not all function templates need to be inlined. An inline function is one that expands its definition in place of its invocation. This can lead to more generated code, but it also buys efficiency because there is no need to set up parameters and call subroutines.

Copyright © 2006-08-29 by Tak Auyeung