#include iostream#include stringusing namespace std;template typename T1 typename T2auto sumT1 x T2 y - decltypex + yauto sumT1 x T2 y return x + y;int main cout sumfloat int101 666 endl; return 0;
-
#include
: 包含输入输出流的标准库。 -
#include
: 包含字符串的标准库。 -
using namespace std: 使用std命名空间,避免在代码中使用std::前缀。
-
template <typename T1, typename T2>: 定义一个模板函数,接受两个类型参数T1和T2。
-
auto sum(T1 x, T2 y) -> decltype(x + y): 定义一个函数sum,使用自动类型推导来确定返回值类型。decltype(x + y)表示返回值类型与x + y的类型相同。
-
{ return x + y; }: 函数体,将x和y相加并返回结果。
-
int main(): 主函数。
-
cout << sum<float, int>(10.1, 666) << endl: 调用sum函数,并将结果输出到标准输出流。模板参数为<float, int>,实参为10.1和666。
-
return 0: 返回0,表示程序正常结束。
原文地址: https://www.cveoy.top/t/topic/iNTT 著作权归作者所有。请勿转载和采集!