候选函数不可行:需要第一个参数的左值

问题描述 投票:0回答:1

我正在尝试编写一个可以像这样组合的函数

doIt(doIt(x, y), z)
但我遇到了错误:
candidate function not viable: expects an l-value for 1st argument
.

这是我的实现。

auto doIt(std::list<std::map<int, std::any>>& x, std::list<std::map<int, std::any>>& y) {
    std::list<std::map<int, std::any>> z(x);
    
    return z;
}

这里有一些我要传入的数据

std::list<std::map<int, std::any>> x = {
    {{0, 1}, {-1, 0.5f}},
    {{0, 0}, {-1, 0.5f}}
};

std::list<std::map<int, std::any>> y = {
    {{0, 1}, {1, 1}, {-1, 0.5f}},
    {{0, 1}, {1, 0}, {-1, 0.5f}},
    {{0, 0}, {1, 1}, {-1, 0.4f}},
    {{0, 0}, {1, 0}, {-1, 0.6f}},
};

std::list<std::map<int, std::any>> z = {
    {{0, 1}, {1, 1}, {-1, 0.5f}},
    {{0, 1}, {1, 0}, {-1, 0.8f}},
    {{0, 0}, {1, 1}, {-1, 0.5f}},
    {{0, 0}, {1, 0}, {-1, 0.6f}},
};

当我按如下方式调用方法时,没有出现错误。

auto _t = doIt(x, y);
_t = doIt(_t, y);

然而,我真正想做的是以下内容。

auto _t = doIt(doIt(x, y), z);

尝试执行上述操作会在 Jupyter Notebook(

xeus-cling
C++17 内核)中出现此错误。

input_line_23:2:2: 错误:没有匹配函数来调用 'doIt'
 做(做(x,y),z)
 ^~~~
input_line_12:1:6:注意:候选函数不可行:需要第一个参数的左值
auto doIt(std::list>& x, std::list>& y) {
     ^

我看了很多其他帖子,但没有一个对我有帮助。我也进行了搜索,但是所解释的内容背后的理论太多了。任何帮助表示赞赏。

根据下面的评论(接受的答案),代码已修改如下并有效。

using _item = std::list<std::map<int, std::any>>;

auto doIt(const _item& x, const _item& y) {
    std::list<std::map<int, std::any>> z(x);
    
    return z;
}
c++ c++17 lvalue
1个回答
2
投票

doIt(x, y)
返回一个临时变量,因此您不能将非常量引用绑定到它,这就是您将它作为第一个参数传递给
doit(..., z)
时尝试做的事情。将该参数声明为
const
参考修复:

auto doIt(const std::list<std::map<int, std::any>>& x, ...
          ^^^^^

其他不写入的参数也是如此。而且,您的代码迫切需要

using
声明,而不是到处重复
std::list<std::map<int, std::any>>

此外,为什么两个不同的变量称为

z
?我建议避免这种情况。

© www.soinside.com 2019 - 2024. All rights reserved.