struct to/from std::tuple conversion

后端 未结 4 1793
[愿得一人]
[愿得一人] 2021-02-05 13:30

Assuming I have struct and std::tuple with same type layout:

struct MyStruct { int i; bool b; double d; }
using MyTuple = std::tuple<         


        
4条回答
  •  逝去的感伤
    2021-02-05 14:12

    Is there any standartized way to cast one to another?

    There is no way to "cast" the one to the other.

    The easiest may be to use a std::tie to pack the tuple out into the struct;

    struct MyStruct { int i; bool b; double d; };
    using MyTuple = std::tuple;
    
    auto t = std::make_tuple(42, true, 5.1);
    MyStruct s;
    
    std::tie(s.i, s.b, s.d) = t;
    

    Demo.

    You can further wrap this up in higher level macros or "generator" (make style) functions, e.g;

    std::tuple from_struct(MyStruct const& src)
    {
      return std::make_tuple(src.i, src.b, src.d);
    }
    
    MyStruct to_struct(std::tuple const& src)
    {
      MyStruct s;
      std::tie(s.i, s.b, s.d) = src;
      return s;
    }
    

    I know that trivial memory copying can do the trick, but it is alignment and implementation dependent?

    You mention the "trivial memory copy" would work - only for copying the individual members. So basically, a memcpy of the entire structure to the tuple and vice-versa is not going to always behave as you expect (if ever); the memory layout of a tuple is not standardised. If it does work, it is highly dependent on the implementation.

提交回复
热议问题