How to define and use boost :: function with "optional arguments"?

I am using a class that needs some kind of callback method, so I am using the boost :: function to store function pointers.

I need a callback to have one optional argument, but I found out that the boost :: function does not allow me to define optional type arguments, so I tried the following code and it worked.

//the second argument is optional typedef boost::function< int (int, char*)> myHandler; class A { public: //handler with 2 arguments int foo(int x,char* a) {printf("%s\n",a); return 0;}; //handler with 1 argument int boo(int x) {return 1;}; } A* a = new A; myHandler fooHandler= boost::bind(&A::foo,a,_1,_2); myHandler booHandler= boost::bind(&A::boo,a,_1); char* anyCharPtr = "just for demo"; //This works as expected calling a->foo(5,anyCharPtr) fooHandler(5,anyCharPtr); //Surprise, this also works as expected, calling a->boo(5) and ignores anyCharPtr booHandler(5,anyCharPtr); 

I was shocked that it worked, the question is, should it work, and is it legal?
is there a better solution?

+4
source share
1 answer

Perhaps this is a safe type hole in the conversion of the bind → function. boost :: bind does not return std :: function, but a function object is of a very complex type. When

 boost::bind(&A::boo,a,_1); 

as shown above, the return object is of type

 boost::_bi::bind_t< int, boost::_mfi::mf1<int,A,int>, boost::_bi::list2<boost::_bi::value<A*>, boost::arg<1> > > 

std :: function only checks that the supplied function object is "compatible", in this case, whether it is callable with int as the first argument and a pointer to char as the second argument. After examining the * boost :: bind_t * template, we see that it really has the corresponding function call operator:

 template<class A1, class A2> result_type operator()(A1 & a1, A2 & a2) 

Inside this function, the second argument ends with a silent drop. This is by design. From the documentation: Any additional arguments are silently ignored (...)

+3
source

Source: https://habr.com/ru/post/1342276/


All Articles