+ 2

Bool Template

Why does this code output 1 and not 2? I get that it is adding booleans, but could someone explain the logic? #include <iostream> using namespace std; template <class T> T sum(T a, T b) { return a+b; } int main () { bool x=true; bool y=true; cout << x << endl; cout << y << endl; cout << sum(x, y) << endl; } https://code.sololearn.com/chzqe7tVGg61/#cpp

11th Aug 2020, 4:17 AM
Edward Finkelstein
Edward Finkelstein - avatar
5 Respostas
+ 2
You're performing arithmetic addition on booleans and the return type is also boolean. The behavior: #include<iostream> bool f(bool a,bool b){ return a+b; } int main() { bool a{true}; bool b{true}; auto c=a+b; std::cout<<typeid(a).name()<<std::endl;//bool std::cout<<typeid(b).name()<<std::endl;//bool std::cout<<typeid(c).name()<<std::endl;//int std::cout<<typeid(f(a,b)).name()<<std::endl;//int return 0; } Explanation: bool+bool gets promoted to int, then gets demoted to bool on the function return
11th Aug 2020, 6:36 AM
Ockert van Schalkwyk
Ockert van Schalkwyk - avatar
+ 2
I don't know c++ but I checked for a little and even when you will return with actual numbers like 3 + 5 the returned value will be 1 so I think it's a problem of the return type so change the return type to int and it will work fine
11th Aug 2020, 5:16 AM
Eliya Ben Baruch
Eliya Ben Baruch - avatar
+ 2
Edward Finkelstein The template parameter T is deduced to bool(I guess that you already knew that) Addition of two bools causes the bools to be promoted to int first. But since your return type is T(which becomes bool in your case),the result of the addition is converted to either a true or false(1 or 0) depending on the result of the addition To get 2 as the answer,just change the return type from T to auto.
11th Aug 2020, 6:47 PM
Anthony Maina
Anthony Maina - avatar
+ 1
Thank you all.
11th Aug 2020, 7:14 PM
Edward Finkelstein
Edward Finkelstein - avatar
+ 1
Ockert van Schalkwyk The last std::cout line in your code outputs b, doesn't that mean bool?
11th Aug 2020, 7:15 PM
Edward Finkelstein
Edward Finkelstein - avatar