When to explicitly specify the template arguments in C++?

Viewed 100

For almost 7 months of studying C++, I've been curious about when to explicitly specify template arguments, specifically function templates.

std::forward is one such example, that should be provided with type template argument (std::forward<Type>(arg)).

Usually, the template arguments are deduced through function parameter types, like:

template <typename T>
void lets_try(T x);

...

lets_try(5) // lets_try<int>(5);

Or, to avoid being deduced, I usually use std::type_identity_t:

template <typename T>
void lets_try(std::type_identity_t<T> x);

...

lets_try(5) // error
lets_try<int>(5) // ok

That's the only thing I've got.

Again, my question is, when should template arguments be specified explicitly? What are the benefits of explicitly specifying them?

1 Answers

when should template arguments be specified explicitly?

When you actually need to specify them explicitly. Otherwise, let the compiler deduce them for you whenever possible.

Sometimes you may need to specify template arguments to resolve ambiguities.

Sometimes you may need to specify template arguments to use specific types/values in a given situation, for instance when you need a type that is different than (but convertible from) a given input value (ex: using std::max<int64_t>(a, b) when a and b are different types, since std::max() only has 1 template argument for both parameters).

Sometimes you may need to specify template arguments that simply have no relation to any function parameters and thus can't be deduced.

Related