9

Is it ok to omit the type after the function name when calling a template function?

As an example, consider the function below:

template<typename T>
void f(T var){...}

Is it ok to simply call it like this:

int x = 5;  
f(x);

Or do I have to include the type?

int x = 5;  
f<int>(x);
gnerkus
  • 11,357
  • 6
  • 47
  • 71
Chris
  • 619
  • 2
  • 9
  • 18
  • 3
    Couldn't you just try it and see what happens? Seems easy enough to test. – Ed S. Jul 17 '09 at 23:17
  • 6
    @ Ed Swangren, The "just try it" method is very uninformative. At best it tells you that a particular compiler allows the given syntax. It tells you nothing about the semantics or correctness of the statement with regards to the language standard. – Trent Jul 17 '09 at 23:32
  • I suppose I could have clarified the question. As Trent kindly pointed out, it wasn't so much of if this will compile. I am curious about what's going on behind the scenes and having a hard time finding good information out there! – Chris Jul 17 '09 at 23:55
  • 1
    @Chris: I don't think the answer you accepted is very good information. It doesn't really even make sense, and it leaves out many details. – Zifre Jul 18 '09 at 00:38

2 Answers2

20

Whenever the compiler can infer template arguments from the function arguments, it is okay to leave them out. This is also good practice, as it will make your code easier to read.

Also, you can only leave template arguments of the end, not the beginning or middle:

template<typename T, typename U> void f(T t) {}
template<typename T, typename U> void g(U u) {}

int main() {
    f<int>(5);      // NOT LEGAL
    f<int, int>(5); // LEGAL

    g<int>(5);      // LEGAL
    g<int, int>(5); // LEGAL

    return 0;
}
Zifre
  • 26,504
  • 11
  • 85
  • 105
11

There is nothing wrong with calling it with implicit template parameters. The compiler will let you know if it gets confused, in which case you may have to explicitly define the template parameters to call the function.

DeusAduro
  • 5,971
  • 5
  • 29
  • 36
  • 1
    Zifre, I think he meant "in which case you may have to explicitly include the template parameters in the function call". – aem Jul 18 '09 at 03:10
  • 1
    I don't talk about calling functions explicitly or implicitly I talk about explicitly defining template parameters... – DeusAduro Jul 18 '09 at 03:49
  • @DeusAduro Can you explain? I think about how functions will be called, and it motivates my design/definitions. Were you making a semantic distinction or did I misunderstand something? – John P Apr 18 '19 at 15:10