Helping the Compiler Deduce the Type of a Template Argument

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
See also  Is Machine Learning Automating Creativity in Graphic Design?

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist