tags:

views:

100

answers:

1

Suppose the following two functions:

#include <iostream>
#include <cstdlib> // atoi
#include <cstring> // strcmp
#include <boost/bind.hpp>

bool match1(const char* a, const char* b) {
    return (strcmp(a, b) == 0);
}

bool match2(int a, const char* b) {
    return (atoi(b) == a);
}

Each of these functions takes two arguments, but can be transformed into a callable object that takes only one argument by using (std/boost)bind. Something along the lines of:

boost::bind(match1, "a test");
boost::bind(match2, 42);

I want to be able to obtain, from two functions like these that take one argument and return bool, a callable object that takes two arguments and returns the && of the bools. The type of the arguments is arbitrary.

Something like an operator&& for functions that return bool.

+9  A: 

The return type of boost::bind overloads operator && (as well as many others). So you can write

boost::bind(match1, "a test", _1) && boost::bind(match2, 42, _2);

If you want to store this value, use boost::function. In this case, the type would be

boost::function<bool(const char *, const char *)>

Note that this isn't the return type of boost::bind (that is unspecified), but any functor with the right signature is convertible to a boost::function.

Jesse Beder
@sth, edited, good suggestion
Jesse Beder
Can I have a function that returns something of type of `boost:bind`?
Helltone
@Helltone, good question - see my edit
Jesse Beder
It works http://gist.github.com/367475 (btw, why `_1` and `_2` are in global namespace?)
J.F. Sebastian
@Sebastian, because it makes it easier to work with? (FYI, they're in an unnamed namespace defined in `boost/bind/placeholders.hpp`.)
Jesse Beder
@Jesse Beder: Lambda uses boost::lambda and Phoenix uses boost::spirit namespace for placeholders, so It is unclear why the Bind library should be any different.
J.F. Sebastian
@Sebastian, it seems to be a popular question. I found this conversation on the boost mailing list: http://lists.boost.org/boost-users/2009/06/48805.php that links to a ticket, but it doesn't look like anything's being done about it. And it seems that `std::bind`'s placeholders will be in `std::placeholder`.
Jesse Beder