c++ - 在 operator= 中使用 std::function 的问题

标签 c++ compiler-errors clang clang++ std-function

我实现了迭代器,我想设置比较函数来设置序列的边界。
所以在构造函数中我接受这个参数

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)到右值。
您可以:
  • 更改间接运算符以返回非常量左值引用(它必须是非常量成员函数)。非常量左值引用参数可以绑定(bind)到非常量左值。
  • 或者更改函数包装器以接受 const 引用。常量左值引用可以绑定(bind)到纯右值。
  • 关于c++ - 在 operator= 中使用 std::function 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61133267/

    相关文章:

    compiler-errors - 此文件不属于任何项目 在 clion 中打开项目时代码洞察可能无法正常工作

    c++ - 如果配置中未使用字段,则修复警告 "field a is not used"的好方法

    c++ - "unix"C++ 预处理器宏未使用 -std=c++11 定义

    c - Linux内核模块: Is it possible to use an open function inside another open function for my module?

    c++ - c 中的快速排序代码,64 位 Windows 机器上无法解释的行为

    java - 我在编写测试驱动程序时遇到了麻烦

    c++ - 通过引用调用 constexpr 方法 - 结果是常量表达式吗?

    c - 为 C 代码生成调用图

    c++ - 如何让我的c++有setenv?

    c++ - 模板 - 巨大的目标文件导致链接器崩溃