使用结构化绑定标记为const的变量不是const

时间:2018-03-15 20:31:08

标签: c++ const c++17 structured-bindings

我一直在编写一组类来允许类似python的zip函数。以下代码片段(几乎)可以正常工作。但是,ab这两个变量不是const

std::vector<double> v1{0.0, 1.1, 2.2, 3.3};
std::vector<int> v2{0, 1, 2};

for (auto const& [a, b] : zip(v1, v2))
{
    std::cout << a << '\t' << b << std::endl;
    a = 3; // I expected this to give a compiler error, but it does not
    std::cout << a << '\t' << b << std::endl;
}

我一直在使用gcc 7.3.0。 这是MCVE:

#include <iostream>
#include <tuple>
#include <vector>

template <class ... Ts>
class zip_iterator
{
    using value_iterator_type = std::tuple<decltype( std::begin(std::declval<Ts>()))...>;
    using value_type          = std::tuple<decltype(*std::begin(std::declval<Ts>()))...>;
    using Indices = std::make_index_sequence<sizeof...(Ts)>;

    value_iterator_type i;

    template <std::size_t ... I>
    value_type dereference(std::index_sequence<I...>)
    {
        return value_type{*std::get<I>(i) ...};
    }

public:
    zip_iterator(value_iterator_type it) : i(it) {}

    value_type operator*()
    {
        return dereference(Indices{});
    }
};

template <class ... Ts>
class zipper
{
    using Indices = std::make_index_sequence<sizeof...(Ts)>;

    std::tuple<Ts& ...> values;

    template <std::size_t ... I>
    zip_iterator<Ts& ...> beginner(std::index_sequence<I...>)
    {
        return std::make_tuple(std::begin(std::get<I>(values)) ...);
    }

public:
    zipper(Ts& ... args) : values{args...} {}

    zip_iterator<Ts& ...> begin()
    {
        return beginner(Indices{});
    }
};

template <class ... Ts>
zipper<Ts& ...> zip(Ts& ... args)
{
    return {args...};
}

int main()
{
    std::vector<double> v{1};
    auto const& [a] = *zip(v).begin();
    std::cout << a << std::endl;
    a = 2; // I expected this to give a compiler error, but it does not
    std::cout << a << std::endl;
}

1 个答案:

答案 0 :(得分:15)

你有一个引用的元组,这意味着引用本身将是const限定的(形式不正确,但在此上下文ignored中),而不是它引用的值。 / p>

int a = 7;
std::tuple<int&> tuple = a;
const auto&[aa] = tuple;
aa = 9; // ok

如果您查看std::get的定义方式,您会看到它为上面的结构化绑定返回const std::tuple_element<0, std::tuple<int&>>&。由于第一个元组元素是引用,const&无效,因此您可以修改返回值。

实际上,如果你有一个类指针/引用成员,你可以在const限定的成员函数(指向/引用的值)中修改它是一回事。

相关问题