【发布时间】:2020-09-03 19:04:19
【问题描述】:
为什么这个 sn-p 不能编译?
#include <iostream>
#include <vector>
#include <ranges>
#include <unordered_map>
namespace vw = std::ranges::views;
int main()
{
auto get_second = [](auto&& pair) constexpr noexcept -> decltype(auto)
{ return std::forward<decltype(pair)>(pair).second; };
std::unordered_map<unsigned, std::pair<double, char> > m = {{5, {0., 'a'}}};
for (auto& [d, c] : m | vw::transform(get_second))
c = 'b';
for (auto const& pair : m)
std::printf("(%u, (%.3f, %c))\n", pair.first, pair.second.first, pair.second.second);
}
错误,使用 gcc 是:
main.cpp: In function 'int main()':
main.cpp:16:53: error: cannot bind non-const lvalue reference of type 'std::pair<double, char>&' to an rvalue of type 'std::__success_type<std::pair<double, char> >::type' {aka 'std::pair<double, char>'}
16 | for (auto& [d, c] : m | vw::transform(get_second))
| ^
-> decltype(auto) 不应该解析为std::pair<double, char>& 吗?如果我将-> decltype(auto) 替换为-> std::pair<double, char>&,它将按预期工作。
【问题讨论】:
标签: c++ lambda c++20 perfect-forwarding