Passing by reference with templates
Aug 26, 2014 at 12:09pm UTC
Hi! Could someone tell me why wouldn't this code compile when adding '<double>' after the function call?
1 2 3 4 5 6 7 8 9 10
template <class T>
T add(T& a, T& b){
return a + b;
}
int main() {
int a, b;
cin >> a >> b;
cout << add<double >(a,b);
}
Compiler error:
cannot convert 'a' (type 'int' ) to type 'double&'
Aug 26, 2014 at 12:15pm UTC
Because you accidentally used int
on line 7 instead of double
. References cannot bind to variables of different types (though const references can bind to temporary conversions).
Aug 26, 2014 at 12:23pm UTC
Oh ok. So that's why it accepts the int
on line 7 if the variables are passed by value.
Thanks!
Topic archived. No new replies allowed.