Explicit Template Argument Specification

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • subi09
    New Member
    • Nov 2012
    • 6

    Explicit Template Argument Specification

    i started reading about templates and i got confused on the below.
    Code:
    template<class T>
    T max(T t1, T t2)
    {
       if (t1 > t2)
          return t1;
       return t2;
    }

    int main(){

    std::cout<<max< int>120,14.55);//=>as per my understanding here if i explicitly mention only one data type,other would be deducted from the argument type(14.55) by the compiler.That means T max(T t1, T t2) instantiates T max(int t1,double t2)in this case.But when i compiled it i got the below warning


    warning: passing double for argument 2 to T max(T, T) [with T = int].Then why this warning came is my question since i have already instantiated for T max(int t1,double t2).

    also since we are using only T,if i mention max<int>,then T max(T t1, T t2) should be like this int max(int t1, int t2) na??

    return 0;

    }

    Please clear my doubts.else i cant proceed further
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Your template only uses T as a parameter. That means you can't use int and double.

    Since the template only returns T you can't return int or double.

    A template is only a pattern. When you specialize the template, the compiler makes a copy of it and replaces the T with the type you specify. This creates the function that will be called.

    You use explicit specialization then certain types require different logic:

    Code:
    template <class T>
    bool IsZero(T arg)
    {
         if (arg) return true;
    	 return false;
    }
    //explicit 
    //do not use the template when T is double
    bool IsZero(double arg)
    {
    	if (fabs(arg) < 0.0001) return false;
    	return true;
    }
    Ths tells the compiler to not use the template if T is double.

    Since bool IsZero(double arg) is an actual function, it will not be in a header file but will be in an implementation file somewhere in the build. Therefore, you need to tip off the compiler that the function exists. You do it this way:

    Code:
    template <class T>
    bool IsZero(T arg)
    {
         if (arg) return true;
    	 return false;
    }
    //explicit specialization
    //do not use the template when T is double
    template<> bool IsZero(double arg);
    }

    Comment

    Working...