在 C++ 计算器中使用模板
working with templates in c++ calculator
template <class A, class B >
A Sum(A Fnum, B Snum){
return Fnum + Snum;
}
template <class S, class W>
S Subtraction(S Fnum, W Snum){
return Fnum - Snum;
}
template <class M, class E>
M Multiplication(M Fnum, E Snum){
return Fnum * Snum;
}
template <class D, class C>
D Division(D Fnum, C Snum){
return Fnum / Snum;
}
我正在尝试做一个计算器程序来了解模板。我想得到一点帮助,我遇到的问题是 - 插入用户输入的号码是什么类型?我的想法是做一个案例 en 提示 1 个数字询问要做什么操作,例如:+/-* 等,然后将这些数字传递给函数......并返回答案,无论他们输入 2 还是 2.567,反之亦然,任何建议??我的模板功能正常吗?他们是否需要任何改进..
添加两个相同类型或类的东西可能更安全,特别是如果
T& operator+( T number );
已超载。如果您正在处理预定义的类型,例如
float, int
那么你不必担心,代码会运行良好。尝试确保算术对于您想要获得的内容有意义,尤其是乘法和除法。
你可能想要类似的东西:
#include<iostream>
using namespace std;
struct Add {
template < typename A, typename B > A operator() (const A & lhs, const B & rhs) { //note return type is A , what if A, B are diff? , you need promote one of them using specialization
return lhs + rhs;
}
};
//some other ops like above
template < typename op, class A, class B > A operate(A Fnum, B Snum)
{
op oper;
return oper(Fnum, Snum);
}
int main()
{
int a = 20, b = 30;
std::cout << operate < Add > (a, b) << std::endl;
}
演示 : http://ideone.com/KReEQ
相关文章:
- 使用 BMI 计算器对C++中的数字进行四舍五入的问题
- 我在c ++矩阵计算器程序中找不到错误
- C++计算器,不能单独除以 0
- 如何正确解析子字符串,以便它们对我的新手计算器有效?
- Arduino 基础 2 计算器无法C++工作
- 需要有关我的平均计算器代码的建议
- C++ - 在我尝试制作一个简单的计算器时有一个"uninitialized local variable y used"警告
- 野牛/flex:计算器将双精度值解释为整数,所以我添加了 YYSTYPE 双精度 #define 但我有多个编译错误
- C++计算器运算符
- 使用WIN32 API的击球平均计算器
- RPN计算器c++错误处理和多个运算符
- C++查找用于构建单行计算器
- 如何修复这个基本计算器
- 用于加法和减法的十六进制计算器
- 桌面计算器出现问题.C++程序设计语言
- 如何对堆栈中的所有项目求和?Postfix计算器
- RPN计算器使用头文件进行计算操作和堆栈;用于堆栈的矢量
- 如何在我的基本计算器中循环遍历数组
- 如果 GPA 计算器的语句问题
- 我的C++计算器似乎出了什么问题?