我使用模板对任何类型的数据添加两个数字,但是没有成功
I used template to add two number for any kind of data types, but it did not work out
应该做哪些更改来接受任何类型的数据?
#include <iostream>
using namespace std;
template <class T>
T add(T n1, T n2)
{
T res;
res = (n1 + n2);
return res;
}
int main()
{
double x, y;
cout << "Enter first number : "; cin >> x;
cout << "Enter second number : "; cin >> y;
cout << add(x, y);
}
您在评论中询问如何添加short和int,或float和double;下面是一个如何在c++ 11和c++ 14中做到这一点的例子。
c++ 11:
template <typename T, typename U>
constexpr auto add( T t, U u ) -> decltype(t + u)
{
return t + u;
}
c++ 14:
template <typename T, typename U>
constexpr auto add( T t, U u )
{
return t + u;
}
你可以这样做:
short a = 31;
long long b = 1234;
std::cout << add(a,b) << 'n';
可能
cout << add<double>(x, y);
add是一个模板方法,必须声明为add(args)
相关文章:
- C++通过数字比较两个数字
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 在 txt 文件中显示前两个数字的程序
- 两个有符号数字之间的距离
- 形成一个斐波那契三角形,使得每个数字是上面左对角线或右对角线上两个数字的总和
- 将数字表示为两个三角形数字的总和
- 两个数字的对称配对功能
- 无法理解代码背后的逻辑,这是在两个给定数字之间生成素数的优化问题
- 查找中间两个数字的正则表达式的匹配项
- 使用C++具有两个数字的最短路径算法.(C++)
- 将两个数字添加为链表
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何对两个 4 位数字进行乘法,将它们视为 C++ 中的多项式
- 在手臂氖中高效计算两个不同的数字
- 如何在 c++ 中添加两个大的双精度数字
- 我应该如何使用remove_if删除两个数字范围内的元素
- C++显示两个区间之间的数字的程序检查一个数字是否可以表示为两个素数的总和
- 是否有任何内置函数可以检查给定的两个数字在给定整数数组中的顺序是否相同?
- 如何在两个不同大小的向量中找到公共数字
- 如何使用C++中不是文字的变量在数字中显示单引号和两个引号?假设 6'2" 英尺