Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omitting arguments in C++ Templates

Tags:

c++

templates

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);
like image 599
Chris Avatar asked Jul 17 '09 22:07

Chris


2 Answers

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;
}
like image 170
Zifre Avatar answered Oct 06 '22 12:10

Zifre


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.

like image 45
DeusAduro Avatar answered Oct 06 '22 12:10

DeusAduro