【发布时间】:2025-12-06 20:30:02
【问题描述】:
我是 C++ 新手,目前正在尝试了解模板函数的工作原理。首先我想添加两个相同类型的数值,这很容易理解。
template <typename T>
T add(T a, T b){return a+b;}
int main(){
float a_f=2.5;float b_f=1.5;float c_f;
int a_i=2;int b_i=1;int c_i;
c_f = add(a_f, b_f);
c_i = add(a_i, b_i);
return 0;
}
接下来我想添加两个不同且相等类型的数字。我天真的假设是这样的:
template<typename R, typename S, typename T>
R add(S a, T b){return a+b;}
int main(){
float a=3.2; int b=2;
auto result1 = add(a,b); // error: no matching function for call to ‘add(float&, int&)’
auto result2 = add(a,a); // error: no matching function for call to ‘add(float&, float&)’
auto result3 = add(b,b); // error: no matching function for call to ‘add(int&, int&)’
return 0;
}
我知道这种方法是不正确的,因为类型名共享一个关于数据类型的交集,因此声明本身不可能是正确的。
如何实现一个简单的 add() 函数,将两个数值相加,而不考虑类型?
【问题讨论】:
标签: c++ templates generic-programming