【发布时间】:2023-01-20 17:03:41
【问题描述】:
我正在做这个练习 18.7C++ 入门加(第 6 版):
我给出的代码是这样的,根据需要使用 lambda 表达式:
#include <iostream>
#include <array>
#include <algorithm>
const int Size = 5;
template <typename T>
void sum(std::array<double, Size> a, T& fp);
int main()
{
double total = 0.0;
std::array<double, Size> temp_c = {32.1, 34.3, 37.8, 35.2, 34.7};
sum(temp_c, [&total](double w){ total += w; });
std::cout << "total: " << total << std::endl;
std::cin.get();
return 0;
}
template <typename T>
void sum(std::array<double, Size> a, T& fp)
{
for (auto pt = a.begin(); pt != a.end(); ++pt)
fp(*pt);
}
我用VSCode编译后,报错了:
cannot bind non-const lvalue reference of type 'main(int, char**)::<lambda(double)>&' to an rvalue of type 'main(int, char**)::<lambda(double)>'。我也查看了官方的答案,它和我的代码几乎一样,并且在编译时给出了同样的错误。我想这是因为void类型函数与模板函数sum中调用的T&类型不匹配,但是问题中要求如何修改代码,同时保持原sum()函数不变呢?我也很困惑为什么会有左值和右值问题在这里。
提前感谢任何答案和解释。
【问题讨论】:
-
提示:如果您将 typedef 替换回错误消息,它看起来像
cannot bind non-const lvalue reference of type 'T&' to an rvalue of type 'T'。是不是比较熟悉?例如,您是否尝试过声明foo(int& x)然后调用foo(1);?看看同样的问题是如何发生的?