Why doesn't this template function prototype work properly?

我是研究僧i 提交于 2021-01-28 07:32:26

问题


If I remove my function prototype and move the function from the bottom to the top everything works fine and the function can accept either a float or and int as a datatype. Aren't you normally supposed to prototype functions? Also, I am a bit curious as to why the function only works if it is at the top. I am pretty sure it is a scoping issue, but it is going over my head for some reason.

#include <iostream>
#include <math.h>
#include <iomanip>

using namespace std;

template <class tyler>              // function template
tyler Addition(tyler, tyler);       // function prototype


int main()
{
setprecision(2); //limits decimal output to 2 places
int num1, num2;
float num3, num4;

cout << "Enter your first number: \n";
cin  >> num1;
cout << "Enter your second number: \n";
cin  >> num2;
cout << num1 << " + " << num2 << " = " << Addition(num1, num2);

cout << "Enter your third number: (round 2 decimal places, e.x. 7.65) \n";
cin >> num3;
cout << "Enter your fourth number: (round 2 decimal places, e.x. 7.65 \n";
cin >> num4;
cout << num3 << " + " << num4 << " = " << Addition(num3, num4);

cin.clear();                // Clears the buffer 
cin.ignore(numeric_limits<streamsize>::max(), '\n');  // Ignores anything left in buffer
cin.get();                  // Asks for an input to stop the CLI from closing.
return 0;
}

tyler Addition(tyler num1, tyler num2)
{
    return (num1 + num2);
}

回答1:


Here's the implementation of the function as it's written:

tyler Addition(tyler num1, tyler num2)
{
    return (num1 + num2);
}

Notice that this is not a template function, and so C++ treats it as though it actually takes in arguments of type tyler rather than treating tyler as a placeholder.

If you want to define the template function later on, that's fine! Just repeat the template header:

/* Prototype! */
template <typename tyler>
tyler Addition(tyler num1, tyler num2)


/* ... other code! ... */


/* Implementation! */
template <typename tyler>
tyler Addition(tyler num1, tyler num2)
{
    return (num1 + num2);
}


来源:https://stackoverflow.com/questions/46637652/why-doesnt-this-template-function-prototype-work-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!