CJCoding With Joseph
15free / daySign inCreate account

Add Two Values of One Type

Write a function template add(T first, T second) that returns first + second. Both parameters use the SAME type parameter T, and the result is returned as a T.

The tests print four results, one per line: add(4, 2), add(2.5, 1.25), add<double>(4, 2.5) and add(std::string("ab"), std::string("cd")).

Why is add(4, 2.5) not one of them? The compiler must find ONE type for T. The 4 says T is int and the 2.5 says T is double, so the call does not compile. Writing add<double>(4, 2.5) chooses T yourself, and the 4 is converted to 4.0 before the function runs.

Do NOT write a main function.

Expected Output:

6
3.75
6.5
abcd

= newline. The output ends with a newline — print one after the last line.

Hints3 available
Topics:
Templates
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.