Explicitly Defined Template Functions

In some situations, a function template can define a group of functions in which, for one function type, the function definition would be inappropriate. For instance, the function template:

    template<class T> int approximate(T first, T second);

determines whether two values are within 5% of each other. The algorithm used for this function template is appropriate for numerical values, but for char* values, it would indicate whether the pointers to two character strings are within 5% of one another , not whether the strings themselves are approximately equal. Whether two pointers are within 5% of each other is not useful information. You can define an explicit template function for char* values to compare the two strings themselves, character by character.

Explicit definition has the same effect on template overloading resolution as explicit declaration (See Overloading Resolution for Template Functions for more information.) If a template function is explicitly defined for:

int approximate(double a, double b) { /* ... */ }

then a call of:

double a=3.54;
float b=3.5;
approximate(a,b);

resolves in a call to approximate(double a, double b) and variable b is converted to type double.



Class Templates


Example of an Explicitly Defined Template Function


Function Templates
Overloading Resolution for Template Functions
Function Template Declarations and Definitions
Differences between Class and Function Templates