tags:

views:

211

answers:

2

When calling a template function, is it ok to omit the type after the function name?

As an example, consider the function

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);

+10  A: 

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
This answer doesn't even make sense. You always call functions explicitly...
Zifre
Zifre, I think he meant "in which case you may have to explicitly include the template parameters in the function call".
aem
I don't talk about calling functions explicitly or implicitly I talk about explicitly defining template parameters...
DeusAduro
+10  A: 

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