我需要创建一个模板函数,它接受用户将输入的值的数量 然后在最后返回总数。我已经完成了一个,并且由于以下原因,它可以很好地处理相同的数据类型 模板特化。但是当使用不同的数据类型(例如 int 和 double)时,它不会:
#include<iostream>
using namespace std;
template <class first, class seconde>
void total (first a, seconde b){
static first m=0;
static seconde f=0;
++f;
if(b==m){
m+=a;
cout<<m<<endl;
}
m+=a;
}
void main(){
total(2,2);
total(1,2);
system("pause");
}
最佳答案
如果您只是想使用模板函数将两个数字相加,您可以这样做:
#include <iostream>
template <typename T1, typename T2, typename rType = double>
rType total(T1 a, T2 b) {
return static_cast<rType>(a + b);
}
int main() {
std::cout << total<int,int>(1,2) << std::endl; //3 - returns double
std::cout << total<int,int,int>(1,2) << std::endl; //3 - returns int
std::cout << total<int,double>(1,2.5) << std::endl; //3.5 - returns double
std::cout << total<double,double>(1.3,2.6) << std::endl; //3.9 - returns double
}
传递第三种数据类型将允许您更改返回类型。
关于c++ - 如何创建一个添加数字的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20382855/