Helping the Compiler Deduce the Type of a Template Argument

The argument type of a function template is normally deduced automatically. For example:

      int n = max (5,10); /* max deduced 
because 5 and 10 are of type int */

However, sometimes the compiler needs more explicit clues regarding the type of the argument, as in the following example:

      template < class T >  T f()  {    return  static_cast< T > (0);  }   int main() {    int  n =  f();//error, can't deduce argument type    double d = f(); //error, can't deduce argument type}

The program fails to compile because the compiler cannot deduce what the type of the argument is. The return type alone is insufficient for that purpose and because the function template f() takes no arguments, the compiler is clueless. In situations like these, C++ enables you state the type of the template explicitly, thereby helping the compiler figure out the template’s argument type:

      int i = f(); //now OK  double d = f(); //ditto
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: