0

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

enter image description here

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

enter image description here

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?

cdahms
  • 3,402
  • 10
  • 49
  • 75

1 Answers1

1

auto is deduced from a return statement. The function declaration doesn't have a return hence is unable to deduce auto. You can guide the compiler

template <typename Num1Type, typename Num2Type>
auto myAdd(Num1Type num1, Num2Type num2) -> decltype(num1 + num2);

After that you will get linker errors, but it's another question.

273K
  • 29,503
  • 10
  • 41
  • 64