结构化绑定实现地下层和std::元组

Structured bindings implementation underground and std::tuple

本文关键字:std 元组 绑定 实现 地下 结构化      更新时间:2023-10-16

是真的吗,clang中的结构化绑定(我使用最近构建的clang version 4.0.0 (trunk 282683))是使用<tuple>中的一些东西实现的,如括号初始化列表可能使用<initializer_list>中的东西?

我写了一些简单的代码,只是为了玩一些最新的功能实现:

struct S { int a; char b; double c; };
auto [a, b, c] = S{1, '2', 3.0};
using A = decltype(a);
using A = int;
using B = decltype(b);
using B = char;
using C = decltype(c);
using C = double;

到目前为止还不错,但是当我在auto之前添加const限定符时:

struct S { int a; char b; double c; };
const auto [a, b, c] = S{1, '2', 3.0};
using A = decltype(a);
using A = int const;
using B = decltype(b);
using B = char const;
using C = decltype(c);
using C = double const;

我得到一个奇怪的错误描述:

In file included from /home/user/test/main.cpp:1:
In file included from /home/user/test/./test.hpp:4:
In file included from /usr/local/bin/../include/c++/v1/utility:193:
/usr/local/bin/../include/c++/v1/__tuple:29:14: fatal error: implicit instantiation of undefined template 'std::__1::tuple_size<S>'
    : public tuple_size<_Tp> {};
             ^
/home/user/test/main.cpp:110:16: note: in instantiation of template class 'std::__1::tuple_size<const S>' requested here
    const auto [a, b, c] = S{1, '2', 3.0};
               ^
/usr/local/bin/../include/c++/v1/__tuple:25:50: note: template is declared here
template <class _Tp> class _LIBCPP_TYPE_VIS_ONLY tuple_size;
                                                 ^

。与意外包含的<tuple>有交互

我知道结构化绑定在clang中部分实现,但无论哪种方式,<tuple>如何与它们相关都很有趣?

我应该包括<tuple>使用结构化绑定吗?

附加:

auto, auto &auto &&可以,但auto constauto const &不行

是的,结构化绑定使用tuple_sizetuple_element作为自定义点。基本规则大致是

  1. 首先处理内置数组;
  2. then check tuple_size<T>::value;
  3. 如果失败,则检查类是否具有所有公共数据成员。

为了使步骤#2可靠地工作,tuple_size需要是sfinae友好的,但tuple_size<cv T>目前不需要是sfinae友好的。