Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function template partial specialization?

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; } 
like image 466
Narek Avatar asked Nov 09 '11 07:11

Narek


1 Answers

Function partial specialization is not yet allowed 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   return 10; } 

In the case of a function templates, only full specialization is allowed by the C++ standard, -- excluding the compiler extensions!

like image 99
iammilind Avatar answered Sep 22 '22 11:09

iammilind