我是 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;
}
Run Code Online (Sandbox Code Playgroud)
接下来我想添加两个具有不同和相同类型的数字。我天真的假设是这样的:
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&)’ …Run Code Online (Sandbox Code Playgroud)