I've written this functor to perform an and operation (&&):
// unary functor; performs '&&'
template <typename T>
struct AND
{
function<bool (const T&)> x;
function<bool (const T&)> y;
AND(function<bool (const T&)> xx, function<bool (const T&)> yy)
: x(xx), y(yy) {}
bool operator() ( const T &arg ) { return x(arg) && y(arg); }
};
// helper
template <typename T>
AND<T> And(function<bool (const T&)> xx, function<bool (const T&)> yy)
{
return AND<T>(xx,yy);
}
Note it's constructor argument types: function<bool (const T&)>
.
Now, I am trying to instantiate it in various ways (inside big_odd_exists()
):
int is_odd(int n) { return n%2; }
int is_big(int n) { return n>5; }
bool big_odd_exists( vector<int>::iterator first, vector<int>::iterator last )
{
function<bool (const int &)> fun1 = is_odd;
function<bool (const int &)> fun2 = is_big;
return any_of( first, last, And( fun1, fun2 ) ); // instantiating an And object
}
int main()
{
std::vector<int> n = {1, 3, 5, 7, 9, 10, 11};
cout << "exists : " << big_odd_exists( n.begin(), n.end() ) << endl;
}
To my surprise, none of the implicit instantiations of the std::functions
would compile.
Here are the cases I've tried (g++-4.8):
This compiles (explicit instantiation of a std::function
object):
function<bool (const int &)> fun1 = is_odd;
function<bool (const int &)> fun2 = is_big;
return any_of( first, last, And( fun1, fun2 ) );
This does not compile (implicit instantiation of a temporary std::function
object):
return any_of( first, last, And( is_odd, is_big ) ); // error: no matching function for call to ‘And(int (&)(int), int (&)(int))’
This compiles (explicit instantiation of a std::function
object):
function<bool (const int &)> fun1 = bind(is_odd,_1);
function<bool (const int &)> fun2 = bind(is_big,_1);
return any_of( first, last, And(fun1, fun2) );
This does not compile (implicit instantiation of a temporary std::function
object):
return any_of( first, last, And(bind(is_odd,_1), bind(is_big,_1)) ); // error: no matching function for call to ‘And(std::_Bind_helper<false, int (&)(int), const std::_Placeholder<1>&>::type, std::_Bind_helper<false, int (&)(int), const std::_Placeholder<1>&>::type)’
As far as I understand, the std::functions
do not have explicit constructors.
So, why can't I use the nicer to read versions of the calls?
I have all the test cases in: http://coliru.stacked-crooked.com/a/ded6cad4cab07541