Home > Enterprise >  Template Argument Deduction with different typename
Template Argument Deduction with different typename

Time:10-11

I have defined a generic function like this:

template <typename T1, typename T2>
T2 Calculation(T1 arg_one, T1 arg_two)
{
    return arg_one   arg_two * 3.14;
}

When I try to use this generic function as follow:

auto sum = Calculation(2, 3.2);

Compiler told me: no matching overloaded function found. However, when I try to use this generic function like Calculation<double, double>, it works fine.

Why compiler couldn't deduce the type of the argument and return value in first sample? I have to explicitly define types?

CodePudding user response:

The problem is that T2 cannot be deduced from any of the function parameters and T2 also doesn't have any default argument, and template parameters can't be deduced from return type.

To solve this either you can either explicitly specify the template argument for T2 when calling the function or change T1 arg_two to T2 arg_two so that T2 can also be deduced just like T1 as shown below:

template <typename T1, typename T2>
//-------------------------vv---------->changed T1 to T2 so that T2 can be deduced from passed second argument
T2 Calculation(T1 arg_one, T2 arg_two)
{
    return arg_one   arg_two * 3.14;
}

auto sum = Calculation(2, 3.2); //works now
  • Related