c++ - boost::signals2::signal gives wrong output? -
i'm new boost library, while practicing example on bind, wrote following code. but, seems 'res' computed but, correct result not transmitted signal. kindly help, wrong in following snippet. the code compiled , run on http://cpp.sh/
#include <iostream> #include<boost/signals2.hpp> using namespace std; class mathobject{ public: int addops(int op1, int op2); }; int mathobject::addops(int op1, int op2){ int res = op1 + op2; cout << "result of addops: " << res << endl; return res; } int main(void){ mathobject mobj; boost::signals2::signal<int(int)> incrementer; incrementer.connect(boost::bind(&mathobject::addops, &mobj, 1, _1)); boost::signals2::signal<int(int)> doubler; doubler.connect(boost::bind(&mathobject::addops, &mobj, _1, _1)); cout << "incrementer of 5" << incrementer(5) << endl; cout << "doubler of 5" << doubler(5) << endl; }
output:
result of addops: 6 incrementer of 51 result of addops: 10 doubler of 51
when signal called, may or may not have handlers connected it. therefore may or may not produce result. default behaviour return result of last-connected handler, if any; or return value indicating "no result". return value of incrementer(5)
, doubler(5)
not int
, rather boost::optional<int>
.
this leads output observe because boost::optional<int>
can implicitly converted bool
, converted output of 1
or 0
.
you need first check result present, , result out of boost::optional<int>
returned:
#include <iostream> #include<boost/signals2.hpp> using namespace std; class mathobject{ public: int addops(int op1, int op2); }; int mathobject::addops(int op1, int op2){ int res = op1 + op2; cout << "result of addops: " << res << endl; return res; } int main(void){ mathobject mobj; boost::signals2::signal<int(int)> incrementer; incrementer.connect(boost::bind(&mathobject::addops, &mobj, 1, _1)); boost::signals2::signal<int(int)> doubler; doubler.connect(boost::bind(&mathobject::addops, &mobj, _1, _1)); boost::optional<int> incremented = incrementer(5); if (incremented) { cout << "incrementer of 5: " << *incremented << endl; } boost::optional<int> doubled = doubler(5); if (doubled) { cout << "doubler of 5: " << *doubled << endl; } }
Comments
Post a Comment