Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No Automatic Cast from `int` to `float` with Template Function

After years of coding in c++, today I was asked a simple question, but indeed I couldn't find its answer and so here I am guys.

Besides wondering why this error is happening, I want to know how I can solve below error by modifying just the template function (without changing the main() function)

template <class T>
T Add(T first, T second)
{
    return first + second;
}

int main()
{
    auto sample_1 = Add(1, 2); // Works
    auto sample_2 = Add(1.f, 2.f); // Works
    auto sample_3 = Add(1.f, 2); // Error: no instance matches the argument types: (double, int)
    return 0;
}
like image 824
Emadpres Avatar asked Oct 02 '15 19:10

Emadpres


1 Answers

Besides wondering why this error is happening,

When you call Add(1.f, 2), the first argument type is float and the second argument type is int.

The compiler has to convert either the first argument to an int or the second argument to a float. Since both of them will require a conversion, they are equally good candidates. One cannot be preferred over the other.

I want to know how I can solve below error by modifying just the template function

You can change the function template to:

template <class T1, class T2>
auto Add(T1 first, T2 second)
{
    return first + second;
}

or to (thanks @PiotrSkotnicki):

template <class T>
T Add(T first, decltype(first) second)
{
    return first + second;
}

In this case, the type of second is not deduced from the argument being passed to the function. Type of first is deduced from the first argument and the type of second is forced to be the same as the type of first.

Add(1.2f, 2);  // The first argument is deduced to be float
               // The second argument is forced to be float.

Add(2, 1.2f);  // The first argument is deduced to be int
               // The second argument is forced to be int.
like image 57
R Sahu Avatar answered Oct 14 '22 14:10

R Sahu