vendredi 2 octobre 2015

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)
{
    T p;
    p = first + second;
    return p;
}

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;
}

Aucun commentaire:

Enregistrer un commentaire