#include <iostream>
#include <boost/bind.hpp>
struct FCall3Templ {
template<typename ARG1, typename ARG2>
ARG1 operator()(ARG1 arg1, ARG2 arg2) {
return arg1+arg2;
}
};
int main() {
boost::bind<int>(FCall3Templ(), 45, 56)(); // call 1
boost::bind<double>(FCall3Templ(), 45.0, 56.0)(); // call 2
return 0;
}
I’m posting the same code that you can find here .
I’m relatively new to meta-programming, boost::bind and operator overloading, but i don’t get get what this code does in some portion of the code and i have this questions:
- why using
operator()without specifying the label for that operator? What is overloading/defining? - how i’m supposed to catch and store the value returned by the 2 calls using an assignment with
T var = ?? - what does it mean the fact that the last
()is empty in both calls ? Is the call for the operator? So what is the name for this technique/operator? - why using the operator overloading this way and not using just a method?
Thanks.
Taking your questions in turn:
1)
operator()is the()operator for an object. For example, if you look at the definition for std::less, it definesoperator()to take two arguments and do a comparison, and return the result. This allows you to write2) In this case, you could catch them like you normally would.
3)
boost::bindis used to take a function-object (an object withoperator()defined), function pointer, or member function pointer optionally along with arguments and returns a new function object (type of which is difficult to describe) that when invoked uses the bound arguments (and possible arguments during the invoke). See the documentation for boost::bindIn this case, the answer is simply calling
boost::bindand then immediatly invoking the result. The second set of()are invoking the result. Since all of the arguments were bound at the timeboost::bindwas called, no additional arguments were necessary.4) And the reason why was that the original question was asking how to make
boost::bindchoose the correct function template instantiation automatically. Unfortunately, when using function pointers (including template functions),boost::bindcannot perform overload resolution automatically, since it has to be passed a single function pointer as it’s first argument, and it is not aware of the how to perform the overload resolution.However, if given a single functor, and that function defines a templated member function
operator()or even an overloadedoperator (), it can perform the overload resolution when it is invoked.