Is it possible to specify only some template parameters when calling a function template and let the compiler deduce the others

Viewed 261

Consider the following function template:

template <typename T1, typename T2>
void foo(T1 a, T2 b){// Do something.}

Now assume that I want T1 to be int, but T2 to be deduced by the compiler depending on the type of b. Something like foo<int,...>(1,b). Is it possible?

Thanks!

2 Answers

Yes!

foo<int>(1, b);

But in that example above there is no benefit. The difference is visible if your first argument would not already be deduced to int:

foo<int>(3.2f, b);
//       ^^^^ Implicit conversion

Answer from Quentin is most convenient.

But there is other way to solve the issue to obvious to come up with it. Since forcing specific template type leads to silent conversion, sometimes it might be more wise to just do explicit conversion.

double x = 1.1;
foo(static_cast<int>(x), boost::lexical_cast<int>(y));

Classic example is use of std::move which only converts to xvalue.

Related