在 C++ 计算器中使用模板

working with templates in c++ calculator

本文关键字:C++ 计算器      更新时间:2023-10-16
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