Optimize Abstract Operations with Function Templates
By Danny Kalev, C++ Pro

When you create a function that performs an abstract operation: copying, reversing and sorting data, you must define multiple versions thereof—one for each datatype. Consider a max() function which returns the higher of its two arguments:


double max(double first, double second);
complex max(complex first, complex second);
date max(date first, date second);
//..additional versions

The programmer must define a separate function for each datatype although the implementation is identical in all these cases:


double max(double first, double second)
{ 
 return first>second? first : second;
}

complex max(complex first, complex second)
{ 
 return first>second? first : second;
}

date max(date first, date second)
{ 
 return first>second? first : second;
}

Not only is the reduplication of code laborious and error-prone, but it's also a fertile source of maintenance and debugging problems. Worse yet, even if you don't use every version of max() in your program, their code still increases the executable's size as most linkers will not remove an unreferenced function from the executable.



Implementing an abstract operation as an ordinary function forces you to define multiple instances of that function, thereby incurring considerable maintenance and debugging overheads.



Use a function template instead of an ordinary function.

  
Next: Using Function Templates

Introduction
Using Function Templates
Additional Performance Issues

Return to Get Help with C/C++ Page

Return to Main Get Help Page


 




Find Out More
Tech Tip: The reverse() Algorithm

Tech Tip: Linker Optimizations

Tech Tip: How to Avoid Code Bloat When Using Templates

Byte Order in Multibyte Values

Standard Template Library Programmer's Guide



TALK BACK
Most compilers' templates support is still rickety: compilation errors pertaining to templates are nearly indecipherable and certain template features may not be supported at all. Worse yet—the syntax isn't always intuitive. Do these facts deter your from using templates more actively in your applications? Would you prefer a different mechanism for implementing generic code? What would it look like?


Sponsored Links