Search code examples
c++templatestemplate-specializationpartial-specialization

Why can I seemingly define a partial specialization for function templates?


I know that the below code is a partial specialization of a class:

template <typename T1, typename T2> 
class MyClass { 
  … 
}; 


// partial specialization: both template parameters have same type 
template <typename T> 
class MyClass<T,T> { 
  … 
}; 

Also I know that C++ does not allow function template partial specialization (only full is allowed). But does my code mean that I have partially specialized my function template for one/same type arguments? Because it works for Microsoft Visual Studio 2010 Express! If no, then could you please explain the partial specialization concept?

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

template <typename T1, typename T2> 
inline T1 max (T1 const& a, T2 const& b) 
{ 
    return a < b ? b : a; 
} 

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


int main ()
{
    cout << max(4,4.2) << endl;
    cout << max(5,5) << endl;
    int z;
    cin>>z;
}

Solution

  • Function partial specialization is not allowed yet as per the standard. In the example, you are actually overloading & not specializing the max<T1,T2> function.
    Its syntax should have looked somewhat like below, had it been allowed:

    // Partial specialization is not allowed by the spec, though!
    template <typename T> 
    inline T const& max<T,T> (T const& a, T const& b)
    {            //    ^^^^^ <--- supposed specializing here as an example
      return a; // can be anything of type T
    }
    

    In the case of a function templates, only full specialization is allowed by the C++ standard.
    There are some compiler extensions which allows partial specialization, but the code looses its portability in such case!