c++ - 如何创建一个添加数字的模板函数

标签 c++ templates

我需要创建一个模板函数,它接受用户将输入的值的数量 然后在最后返回总数。我已经完成了一个,并且由于以下原因,它可以很好地处理相同的数据类型 模板特化。但是当使用不同的数据类型(例如 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/

相关文章:

c++ - 如何将 C++ 程序与 HTML 页面链接起来?

c++ - 类模板中没有扣除

C++如何使用其中也包含此类的类中的枚举

c++ - 使用类的非模板版本作为父类

c++ - 在模板类中使用函数指针

c++ - 当相同的约束必须推导不同的类型时,为什么将概念放入类型说明符会导致类型推导失败?

c++ - 为使用数组、 vector 、结构等传递给可变参数函数或可变参数模板函数的所有参数指定一种类型?

c++ - 如何用这个类的其他成员数据初始化一个类成员数据?

c++ - 如何在Visual Studio 2017和C++中自动生成注释?

c++ - 在 C++ 的链接列表方法中,如何将参数默认为其最后一个索引?