【发布时间】:2018-12-13 17:20:01
【问题描述】:
我有一个类应该根据用户提供的谓词过滤其内容。给我的界面规定了对谓词的引用:
class Test {
vector<int> data;
public:
template <class PREDTYPE>
void filter(PREDTYPE& pred) {
return;
}
};
我还给了一段测试代码,大致是这样的:
class Filter {
public:
bool operator()(int) const {
return false;
}
};
int main() {
Test test;
test.filter(Filter());
}
这不编译,说cannot bind non-const lvalue reference of type 'Filter&' to an rvalue of type 'Filter'。如果我将测试代码更改为
int main() {
Test test;
Filter filter;
test.filter(filter);
}
它有效,但这取决于最终用户,我无法控制他们的行为。我尝试重载过滤器方法,创建一个可以按值接受谓词然后通过引用传递它的版本,但这也无法编译,并显示消息call of overloaded 'filter(Filter&)' is ambiguous。
因此我的问题是:是否可以构造一个同时接受谓词的右值和左值的过滤器?
【问题讨论】:
标签: c++ templates function-object