【发布时间】:2019-07-25 07:51:11
【问题描述】:
我很好奇this asked 问题如下:
#include <iostream>
#include <set>
#include <iterator>
#include <array>
#include <tuple>
#include <type_traits>
int main()
{
const std::set<int> s{ 0, 1, 2, 3, 4, 5, 6, 7, 8 };
auto iter = s.find(5);
using IterType = decltype(iter);
// using `std::array` works fine!
const auto& [pv1, nxt1] = std::array<IterType, 2>{std::prev(iter), std::next(iter)};
std::cout <<"using std::array<IterType, 2> :"<< *pv1 << " " << *nxt1 << '\n'; // prints: 4 6
// using ` std::make_tuple` works fine!
const auto& [pv2, nxt2] = std::make_tuple(std::prev(iter), std::next(iter));
std::cout << "using std::make_tuple :" << *pv2 << " " << *pv2 << '\n'; // prints: 4 6
// using `std::tie` deduction happens in MSVC, but not in GCC and Clang
const auto& [pv3, nxt3] = std::tie(std::prev(iter), std::next(iter));
// following is an assertion failure in MSVC with /O2 /std:c++17
std::cout << "using std::tie :" << *pv3 << " " << *nxt3<< '\n';
}
我 std::tie d 返回了 std::prev 和 std::next 的迭代器,并允许
结构化绑定做auto的推演。
const auto& [pv3, nxt3] = std::tie(std::prev(iter), std::next(iter));
看起来它允许的唯一编译器是带有/O2 /std:c++17的MSVC v19.14!
GCC 9.1 和 clang 8.0 不同意这一点。见在线编译器:https://godbolt.org/z/DTb_OZ
GCC 说:
<source>:23:28: error: no matching function for call to 'tie'
const auto& [pv3, nxt3] = std::tie(std::prev(iter), std::next(iter));
^~~~~~~~
/opt/compiler-explorer/gcc-8.3.0/lib/gcc/x86_64-linux-gnu/8.3.0/../../../../include/c++/8.3.0/tuple:1605:5: note: candidate function [with _Elements = <std::_Rb_tree_const_iterator<int>, std::_Rb_tree_const_iterator<int>>] not viable: expects an l-value for 1st argument
tie(_Elements&... __args) noexcept
^
Clang 说:
<source>: In function 'int main()':
<source>:23:46: error: cannot bind non-const lvalue reference of type 'std::_Rb_tree_const_iterator<int>&' to an rvalue of type 'std::_Rb_tree_const_iterator<int>'
23 | const auto& [pv3, nxt3] = std::tie(std::prev(iter), std::next(iter));
| ~~~~~~~~~^~~~~~
In file included from <source>:5:
/opt/compiler-explorer/gcc-9.1.0/include/c++/9.1.0/tuple:1611:19: note: initializing argument 1 of 'constexpr std::tuple<_Elements& ...> std::tie(_Elements& ...) [with _Elements = {std::_Rb_tree_const_iterator<int>, std::_Rb_tree_const_iterator<int>}]'
1611 | tie(_Elements&... __args) noexcept
| ~~~~~~~~~~^~~~~~~~~~
查看cppreference.com 中给出的示例 MSVC 是正确的吗?或谁在这里,为什么?
有趣的同时运行
std::cout << "using std::tie :" << *pv3 << " " << *nxt3<< '\n';
给我
(在 MSVS 2019 中,/std:c++17)
【问题讨论】:
-
对编译器启用
/Za标志,则代码将被拒绝。 MVSC 具有允许将临时绑定到左值引用的扩展。tie获取左值引用,但prev,next临时返回。 -
我认为结构化绑定与这个问题没有任何关系。尝试
const auto& x = ...代替他们,问题仍然存在。 -
@MaxLanghof 当仔细观察问题变得清晰时,有时问题(或最初的直觉)在开始时可能毫无意义。这就是发生在我身上的事!
标签: c++ iterator c++17 structured-bindings std-tie