我使用模板对任何类型的数据添加两个数字,但是没有成功

I used template to add two number for any kind of data types, but it did not work out

本文关键字:数字 两个 成功 任何 添加 数据 类型      更新时间:2023-10-16

应该做哪些更改来接受任何类型的数据?

#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)