Omitting arguments in C++ Templates

c++, templates

Solution

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

Problem

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

Original source