【问题标题】:can template function have multiple return type?模板函数可以有多种返回类型吗?
【发布时间】:2020-04-17 07:08:41
【问题描述】:

我是一名学生。我正在使用模板执行算术运算(减法、加法、乘法、除法),但遇到了一些困难:

一些算术运算(减法,乘法,除法)没有运行?我想使用模板运行所有算术运算

节目链接: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/

【问题讨论】:

  • 不,单个函数只能到达单个返回语句。您必须为每个操作定义一个单独的函数(可能添加一个表示算术运算的模板参数到现有函数)或将所有这些结果打包到一个向量/数组/结构/任何东西中。
  • 您误解了模板的用途。模板允许您编写一个对许多不同类型进行操作的函数。这并不意味着你可以编写一个返回多个值的函数。
  • @john 我面临错误“T”没有命名类型onlinegdb.com/SJMWk1v_8帮助
  • @rahul_ 您需要将template &lt;class T&gt; 放在所有函数之前,而不仅仅是第一个函数。
  • @john 现在运行良好我可以在上述问题中添加解决方案

标签: c++ templates


【解决方案1】:

模板与您获得的结果无关。 模板可用于处理多种类型而不是多个值。

函数一遇到返回就退出,所以只执行你的函数的第一个操作,其他的被完全忽略,因为第一个操作的代码退出返回:

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

【讨论】:

  • 我可以在哪里传递值 x(10) 和 y(5) ?
  • 你仍然可以像以前一样调用 arithmaticop int main() { cout (10, 5); }
猜你喜欢
  • 1970-01-01
  • 2021-08-30
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 2012-10-25
  • 1970-01-01
  • 1970-01-01
  • 2012-06-21
相关资源
最近更新 更多