Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between Template Explicit Specialization and ordinary function?

Tags:

c++

templates

template <class T>
void max (T &a ,T &b)
{}//generic template   #1

template<> void max(char &c, char &d)
{} //template specializtion    #2

void max (char &c, char &d)
{}//ordinary function      #3

what is difference between 1 ,2, and 3?

like image 722
Suri Avatar asked Apr 28 '10 10:04

Suri


2 Answers

  1. is a template function
  2. is a total specialization of the previous template function (doesn't overload!)
  3. is an overload of the function

Here is an excerpt from C++ Coding Standards: 101 Rules, Guidelines, and Best Practices:

66) Don't specialize function templates

Function template specializations never participate in overloading: Therefore, any specializations you write will not affect which template gets used, and this runs counter to what most people would intuitively expect. After all, if you had written a nontemplate function with the identical signature instead of a function template specialization, the nontemplate function would always be selected because it's always considered to be a better match than a template.

The book advises you to add a level of indirection by implementing the function template in terms of a class template:

#include <algorithm>

template<typename T>
struct max_implementation
{
  T& operator() (T& a, T& b)
  {
    return std::max(a, b);
  }
};

template<typename T>
T& max(T& a, T& b)
{
  return max_implementation<T>()(a, b);
}

See also:

  • Why Not Specialize Function Templates?
  • Template Specialization and Overloading
like image 177
Gregory Pakosz Avatar answered Nov 15 '22 20:11

Gregory Pakosz


The matching rules for template parameters subtly differ from that of overloaded functions. An example of what differs can be seen when you try to invoke max() with arguments of different tyoes:

max(1,'2');

This will match the overloaded function, but neither the base template nor the specialization.

like image 21
sbi Avatar answered Nov 15 '22 19:11

sbi