'Why result1 and result2 have same value instead the <int> was missing from result2 line?

#include <iostream>
using namespace std;

template <typename T>
T add(T num1, T num2) {
    return (num1 + num2);
}

int main() {
    int result1;
    int result2;
    // calling with int parameters
    result1 = add<int>(2, 3);
    cout << "2 + 3 = " << result1 << endl;
     

    result2 = add(2,3);
    cout << "2 + 3 = "<< result2<<endl;

    return 0;
}

The <int> is missing but the code runs without any error Why so? Is it necessary to add the part?



Solution 1:[1]

Why so?

Because of template argument deduction:

In order to instantiate a function template, every template argument must be known, but not every template argument has to be specified. When possible, the compiler will deduce the missing template arguments from the function arguments. This occurs when a function call is attempted, when an address of a function template is taken, and in some other contexts:

(end quote)

This means that for your 2nd call expression add(2,3), the template type parameter T is automatically deduced to be int from the function call arguments 2 and 3.

While for the call expression add<int>(2,3), you're explicitly specifying the template argument as int and in this case there will be no template argument deduction.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1