Omitting Arguments in C ++ Templates

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

As an example, consider the function

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

Can one simply call it like this:

int x = 5;
F (X);

or do i need to enable type?

int x = 5;
e <int > (x);

+6
c ++ templates
source share
2 answers

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

In addition, you can leave the arguments to the end pattern, rather than 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; } 
+17
source share

There is nothing wrong with invoking it with implicit template parameters. The compiler will tell you if it is confused, in which case you may need to explicitly define the template parameters for calling the function.

+10
source share

All Articles