Is it possible to trivially copy the template template :: std :: tuple? Is there an implementation?

I need a trivially copied class, like a tuple, but there are no suitable implementations, I could not come up with it myself, and I think that it may even be impossible. The reason for this is the links. A ::std::tuple may contain references, but a trivially copied tuple may not be possible, since it may not have non-trivial constructors and references that must be initialized in constructors of type like a tuple, and store the reference shell to make a class similar to a tuple, non-trivial. My questions are indicated in the title.

+6
source share
2 answers

Saving links using reference_wrapper possible:

std::reference_wrapper guaranteed to be TriviallyCopyable. (since C ++ 17)

Just having a non-trivial nonspecific constructor (e.g. std::reference_wrapper<T>::reference_wrapper(T&) ) is absolutely normal. The same goes for your trivially_copyable_tuple ; if it has a trivial copy constructor, trivially_copyable_tuple::trivially_copyable_tuple(int&, float&, char) fine.

And generally, you do not need to use std::reference_wrapper ; while the reference type is not TriviallyCopyable, the class type containing the link itself is TriviallyCopyable (although it is not Pod, StandardLayoutType, DefaultConstructible, TriviallyDefaultConstructible or Trivial).

Here are some examples:

  • my own set of tuples , showing that no special tricks are required to create it TriviallyCopyable;
  • a slightly more complicated implementation showing that if you provide reassignment of assignability (so you need to use reference_wrapper -alike inside), you can still save all other properties;
  • a assignable tuple showing that you are losing the trivial ability to copy, but only on tuples that actually contain a reference type; you can keep the trivial ability to copy on tuples containing scalars.
+6
source

It is unclear what you mean when discussing links.

Yes, if there is any particular type of stored reference types, then it will not be trivially copied. But this is true for any type. If the type is not trivially copied, then the type that contains this type as a subobject cannot also be trivially copied.

You cannot write a tuple that imposes trivial copyability on types that alone cannot be trivially copied.

But otherwise, it is possible to write a type of tuple that will be trivially copied if all types of components themselves are trivially copied. This is the best guarantee you will receive. And if you want users to never provide types that are not subject to trivial copying, you can always add static_assert that all types in the type list can be trivially copied.

+6
source

All Articles