Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Intermediate
Nov 5, 1999

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<int> 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<int>(); //now OK
  double d = f<double>(); //ditto
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap