简体   繁体   中英

How to convert a homogeneous fusion::vector to an (std/boost)::array

I am relatively new to boost, so I believe this is an easy problem:
Given, say a fusion::vector<int, int, int> , I need a good way to turn it into an array<int, 3> .

You can just use the builtin adaption of array<> (std or boost) and copy :

Live On Coliru

#include <boost/fusion/include/copy.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/adapted/boost_array.hpp>
#include <boost/array.hpp>

using namespace boost;

int main() {
    fusion::vector<int, int, int> fv(1,2,3);
    array<int, 3> arr;

    fusion::copy(fv, arr);
}

Building on @sehe's answer you can also use fusion::invoke to get rid of the uninitialized array.

#include <boost/fusion/functional/invocation/invoke.hpp>

#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/adapted/boost_array.hpp>
#include <boost/array.hpp>

using namespace boost;

#include <iostream>
int main() {
    fusion::vector<int, int, int> fv(1,2,3);

    auto arr = fusion::invoke([](int x, int y, int z){return array<int, 3>{x, y, z};}, fv);

    for(auto i : arr)
        std::cout << i << " ";
}

which becomes more attractive in C++14

    auto arr = fusion::invoke([](auto... xs){return array<int, 3>{xs...};}, fv);

and in C++17

    auto arr = fusion::invoke([](auto... xs){return std::array{xs...};}, fv);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM