21

我一直在编写一组类来允许一个简单的类似 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;
}
4

1 回答 1

20

您有一个引用的元组,这意味着引用本身将被const限定(格式不正确,但在此上下文中被忽略),而不是它引用的值。

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合格成员函数中修改的类指针/引用成员(即指向/引用的值),那也是一样的。

于 2018-03-15T20:58:59.057 回答