template function call with empty angle brackets <>

Ibrahim Quraish picture Ibrahim Quraish · Dec 5, 2013 · Viewed 6.9k times · Source

I am confused with the below template behavior, where it compiles fine with the empty angle brackets (template without parameters) since syntactically, template<> is reserved to mark an explicit template specialization.

template <typename T> void add(T a, T b) { }
int main() {
    add<>(10, 3); // compiles fine since both parameters are of same data type
    add<>(10, 3.2); // Error: no matching function for call to add(int, double)
}

In the above case is the template parameter really optional?

Answer

Mike Seymour picture Mike Seymour · Dec 5, 2013

template<> is reserved to mark an explicit template specialization.

It means various things, depending on context. Here it means "use the default or deduced argument", just as if you simply said add.

In the first case, both function arguments have the same type, so the template argument can be deduced as int.

In the second case, they have different types, so the template argument can't be deduced. You'd have to specify what you want, e.g. add<double>, convert one function argument to match the other, or modify the template to parametrise each type separately.

In the above case is the template parameter really optional?

Yes, if it can be deduced from the argument types.