Thursday, 1 August 2013

Introduction to C++ templates ( Function Templates)


//max.h

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

  • T is template paramter. ( There can be more than one template params)
  • a and b are call parameters.
  • Look at return type it is const T& , function returns the max of two by ref to const. 
  • It is evil to return values by ref. or pointer if they are local to function. 
  • But it is ok to return temporaries by reference to const only. (the scope is extended outside the function and return value optimisation kicks in.
  • Returning by ref to non-const is not allowed as ref to non-const are bound to lvalues and temporaries are not lvalues they are nameless objects.
  • Template function can be used as follows.
//max.cpp
std::cout << max(2,3);
int a = 20; ::max(10,a)
std::string s1 = "Mandar" , s2 ="MandarVaidya";::max(s1,s2);
std::complex<float> c1, c2;...::max(c1, c2) ;  // (1) error as > operator is not supported.
  • max is qualified with :: so that correct max is called as there is std::max(), we don't want to call that function.
  • Templates are compiled twice, one without instantiation to check for syntax
  • Second at the time of instantiation to check if all the calls are valid e.g. unsupported calls as reported as "compile time" errors. such as (1)
  • For each type new template function is instantiated as shown about.
  • max(2,3); // arguments deduced as int
  • max(2.0,2); //error both args should be of same type
  • max<double>(2,5); //OK
  • max(static_cast<double>(2),5.3);  //OK

Variation - 1

  • Look at return type it is no longer ref. it is an object of type T1
  • During return if T2 object is converted to T1 (depending on result of comparison) and for that local temporary is created and it cannot be returned by reference. Hence return is done by value. ( copy ctor will be called )
  • max(42, 66.66); will return 66 as T1 is int here.
  • max(66.66, 42); will return 66.66 as T1 is double.
  • drawbacks return type is fixed and order of arguments varies the result.

Variation -2 

  • Return type is specified as double and other two types are deduced form the arguments.
const double& max (double const&, double const&);
const std::string& max (std::string const&, std::string const&); 

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


template<typename T1, typename T2, typename ReturnType)
inline ReturnType max(const T1& a, const T2& b);

max<int, double, double>(2,3.3); //OK 
  • Tedious way to specify return type.

simplification

template<typename ReturnType, typename T1, typename T2>
inline ReturnType max(const T1& a, const T2& b);

max<double>(10,20); //OK 

  • Return type is specified as double types T1 and T2 are omitted but will be deduced form the called arguments.

No comments:

Post a Comment