【发布时间】:2013-10-16 10:11:49
【问题描述】:
我编写了这个函子来执行 and 操作(&&):
// 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);
}
注意它是构造函数参数类型:function<bool (const T&)>。
现在,我正在尝试以各种方式实例化它(在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;
}
令我惊讶的是,std::functions 的所有隐式实例都无法编译。
以下是我尝试过的案例(g++-4.8):
这会编译(显式 std::function 对象的实例化):
function<bool (const int &)> fun1 = is_odd;
function<bool (const int &)> fun2 = is_big;
return any_of( first, last, And( fun1, fun2 ) );
这不编译(隐式临时std::function对象的实例化):
return any_of( first, last, And( is_odd, is_big ) ); // error: no matching function for call to ‘And(int (&)(int), int (&)(int))’
这编译(显式 std::function 对象的实例化):
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) );
这不编译(隐式临时std::function对象的实例化):
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)’
据我了解,std::functions 确实 没有 有明确的构造函数。
那么,为什么我不能使用 nicer 来阅读 版本的调用呢?
我有所有的测试用例: http://coliru.stacked-crooked.com/a/ded6cad4cab07541
【问题讨论】:
-
检查函数
is_big和is_odd的返回类型,并与您尝试创建的std::function对象的返回类型进行比较。 -
@JoachimPileborg :他们返回一个
int,我正在尝试创建一个function<bool (const int &)>。那么,int作为参数有什么问题呢? -
返回
int的函数永远不会与返回bool的函数相同。 -
@JoachimPileborg:是的,你是对的。不幸的是,这并没有什么区别,因为即使我将
is_odd定义为bool is_odd(const int &),编译器也无法推断出T是什么类型。