Structured binding and tie()

人走茶凉 提交于 2019-12-01 15:43:52

Nope.

Structured bindings has specific language rules to handle arrays and certain other types. tie() is specifically a tuple<T&...> and can only be assigned from another tuple<U&...>.


With the array case, you can write a function to turn that array into a tuple of references into it:

template <typename T, size_t N, size_t... Is>
auto as_tuple_impl(T (&arr)[N], std::index_sequence<Is...>) {
    return std::forward_as_tuple(arr[Is]...);
}

template <typename T, size_t N>
auto as_tuple(T (&arr)[N]) {
    return as_tuple_impl(arr, std::make_index_sequence<N>{});
}

std::tie(x1, y1, z1) = as_tuple(a); // ok

Alternatively, if you know how many bindings there are (which you have to anyway), you can use structured bindings as give back a tuple. But you have to both specify the size and write out a case for each one:

template <size_t I, typename T>
auto as_tuple(T&& tuple) {
    if constexpr (I == 1) {
        auto&& [a] = std::forward<T>(tuple);
        return std::forward_as_tuple(a);
    } else if constexpr (I == 2) {
        auto&& [a, b] = std::forward<T>(tuple);
        return std::forward_as_tuple(a, b);
    } else if constexpr (I == 3) {
        // etc.
    }
}

std::tie(x1, y1, z1) = as_tuple<3>(a); // ok

Just for fun... to simulate a syntax similar to

std::tie(x1,y1,z1) = a;

you can write a struct that wrap an array of pointers, with an operator=() for corresponding arrays

template <typename T, std::size_t ... Is>
struct ptrArray<T, std::index_sequence<Is...>>
 {
   std::array<T*, sizeof...(Is)> ap;

   auto & operator= (T (&arr)[sizeof...(Is)])
    {
      ((*ap[Is] = arr[Is]), ...);

      return *this;
    }
 };

and a make-function for this structure

template <typename T0, typename ... Ts>
ptrArray<T0, std::make_index_sequence<sizeof...(Ts)+1U>>
   makePtrArray (T0 & t0, Ts & ... ts)
 { return { { { &t0, &ts... } } }; }

and

makePtrArray(x1, y1, z1) = a;

works.

The following is a full working example

#include <array>
#include <iostream>
#include <type_traits>

template <typename, typename>
struct ptrArray;

template <typename T, std::size_t ... Is>
struct ptrArray<T, std::index_sequence<Is...>>
 {
   std::array<T*, sizeof...(Is)> ap;

   auto & operator= (T (&arr)[sizeof...(Is)])
    {
      ((*ap[Is] = arr[Is]), ...);

      return *this;
    }
 };

template <typename T0, typename ... Ts>
ptrArray<T0, std::make_index_sequence<sizeof...(Ts)+1U>>
   makePtrArray (T0 & t0, Ts & ... ts)
 { return { { { &t0, &ts... } } }; }

int main ()
 {
   int x1, y1, z1;
   int a[3] {10,20,30};

   makePtrArray(x1, y1, z1) = a;

   std::cout << x1 << ' ' << y1 << ' ' << z1 << std::endl;
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!