【问题标题】:Problem with using std::function in operator=在 operator= 中使用 std::function 的问题
【发布时间】:2020-04-10 02:44:36
【问题描述】:

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

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)) {}

next... 我尝试在 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;

如何解决?

或者..我可以用另一种方式制作那个界面吗?

【问题讨论】:

  • 您的operator*() 方法是否返回引用?
  • @0x499602D2, no, "T operator*() const { return gen.current_num(); }"
  • 好的,把你的function签名改成std::function&lt;bool(T const&amp;, T const&amp;)&gt;

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


【解决方案1】:
T operator*() const { return gen.current_num(); }

const std::function<bool(T&, T&)> cmp

cmp(**this, *rhs);

有问题。错误消息解释它:

错误:没有用于调用的匹配函数...候选函数不可行:第一个参数需要一个左值

cmp 接受非常量左值引用。间接运算符返回一个纯右值。非 const 左值引用不能绑定到右值。

您可以:

  • 更改间接运算符以返回非常量左值引用(它必须是非常量成员函数)。非常量左值引用参数可以绑定到非常量左值。
  • 或者将函数包装器改为接受 const 引用。 const 左值引用可以绑定到纯右值。

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 2022-11-04
    • 2017-07-25
    • 2019-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    相关资源
    最近更新 更多