KMot
KMot

Reputation: 507

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

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!

Upvotes: 2

Views: 1013

Answers (2)

Marek R
Marek R

Reputation: 37852

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.

Upvotes: 0

Quentin
Quentin

Reputation: 63124

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

Upvotes: 3

Related Questions