我是学生。我正在使用模板执行算术运算(减法,加法,乘法,除法),但面临一些困难:
一些算术运算(减法,乘法,除法)未运行?我想使用模板运行所有算术运算
节目链接:https://onlinegdb.com/r1RUMCU_8
程序:
#include <iostream>
using namespace std;
template <class T>
T arithmaticop(T x, T y) //pass data type as a parameter
{
return x+y;
return x*y;
return x/y;
return x-y;
}
int main()
{
cout << arithmaticop<int>(10, 5);
}
o / p
15 //这里仅给出唯一的附加
我引用此链接:http://www.cplusplus.com/doc/oldtutorial/templates/
最佳答案
模板与您获得的结果无关。
模板可用于处理多种类型,而不是多种值。
该函数在遇到返回后立即退出,因此只有执行了该函数的第一个操作,其他操作才被完全忽略,因为带有第一个操作的代码退出返回:
return x+y
如果您希望代码执行列出的所有操作并仅打印结果,则可以执行以下操作:
#include <string>
#include <sstream>
template <class T>
std::string arithmaticop(T x, T y) //pass data type as a parameter
{
std::stringstream resultStringStream;
resultStringStream << x+y;
resultStringStream << x-y;
resultStringStream << x*y;
resultStringStream << x/y;
return resultStringStream.str();
}
关于c++ - 模板函数可以有多个返回类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61265879/