我实现了迭代器,我想设置比较函数来设置序列的边界。
所以在构造函数中我接受这个参数
iterator(std::pair<T, std::function<T(T&)>> rhs, const std::function<bool(T&, T&)> cmp):
base(rhs), cmp(cmp), gen(range<T>::gen_function(rhs)) {}
接下来...我尝试在 operator== 中使用 cmp 仿函数:
bool operator==(const iterator& rhs) const { return cmp(**this, *rhs); }
bool operator!=(const iterator& rhs) const { return !cmp(**this, *rhs); }
由 clang++ 编译(v 11.0.0,Ubuntu 18)
clang++ -std=c++2a -stdlib=libc++ coroutins_iterator.cpp -v
并且编译器给了我错误:
./coroutins_iterator.h:52:56: error: no matching function for call to object of type 'const std::function<bool (int &, int &)>'
bool operator!=(const iterator& rhs) const { return !cmp(**this, *rhs); }
^~~
coroutins_iterator.cpp:31:14: note: in instantiation of member function 'range<int>::iterator::operator!=' requested here
for (auto a : range<int>(2, 10, [](int &a){ return a * 2; })) {
^
/usr/include/c++/v1/functional:2342:9: note: candidate function not viable: expects an l-value for 1st argument
_Rp operator()(_ArgTypes...) const;
如何解决?
或者..我可以用另一种方式制作那个界面吗?
最佳答案
T operator*() const { return gen.current_num(); } const std::function<bool(T&, T&)> cmp cmp(**this, *rhs);
有问题。错误消息解释它:
error: no matching function for call ... candidate function not viable: expects an l-value for 1st argument
cmp
接受非常量左值引用。间接运算符返回一个纯右值。非常量左值引用不能绑定(bind)到右值。您可以:
关于c++ - 在 operator= 中使用 std::function 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61133267/