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);
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With