I'm trying to understand function templates when used in function prototypes in C++ better. I'll jump right into my question, this works:
// my_prog.cpp
#include <iostream>
#include <vector>
template <typename Num1Type, typename Num2Type>
auto myAdd(Num1Type num1, Num2Type num2)
{
return num1 + num2;
}
int main()
{
int a1 = 2;
int a2 = 2;
int result1 = myAdd(a1, a2);
std::cout << "\n" << "result1 = " << result1 << "\n";
double b1 = 2.2;
double b2 = 2.2;
double result2 = myAdd(b1, b2);
std::cout << "\n" << "result2 = " << result2 << "\n";
int c1 = 2;
float c2 = 2.2;
double result3 = myAdd(c1, c2);
std::cout << "\n" << "result3 = " << result3 << "\n";
return 0;
}
this does not:
// my_prog.cpp
#include <iostream>
#include <vector>
// function prototypes
template <typename Num1Type, typename Num2Type>
auto myAdd(Num1Type num1, Num2Type num2);
int main()
{
int a1 = 2;
int a2 = 2;
int result1 = myAdd(a1, a2);
std::cout << "\n" << "result1 = " << result1 << "\n";
double b1 = 2.2;
double b2 = 2.2;
double result2 = myAdd(b1, b2);
std::cout << "\n" << "result2 = " << result2 << "\n";
int c1 = 2;
float c2 = 2.2;
double result3 = myAdd(c1, c2);
std::cout << "\n" << "result3 = " << result3 << "\n";
return 0;
}
template <typename Num1Type, typename Num2Type>
auto myAdd(Num1Type num1, Num2Type num2)
{
return num1 + num2;
}
As you can see I'm using HackerRank CodePair as my editor.
I've read some information on how C++ templates work when function prototypes are used, for example:
Template and prototype in class
Prototyping a template function in C++
Why doesn't this template function prototype work properly?
https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl
But I'm still not sure how to change the 2nd program above to get past the error. Any suggestions? Is this even possible?