I need a trivially copyable tuple-like class, but no suitable implementations exist, I could not come up with one myself and I think one might even not be possible. The reason for it are references. A ::std::tuple
can hold references, but a trivially copyable tuple might not be able to, since it may not have non-trivial constructors and references would have to be initialized in the constructors of the tuple-like class and storing a reference wrapper would make the tuple-like class non-trivial. My questions are in the title.
Storing references using reference_wrapper
is entirely possible:
std::reference_wrapper
is guaranteed to be TriviallyCopyable. (since C++17)
Just having a non-trivial non-special constructor (as e.g. std::reference_wrapper<T>::reference_wrapper(T&)
) is absolutely fine. So the same holds for your trivially_copyable_tuple
; as long as it has a trivial copy constructor, trivially_copyable_tuple::trivially_copyable_tuple(int&, float&, char)
is fine.
And actually, you don't need to use std::reference_wrapper
at all; while a reference type is not TriviallyCopyable, a class type containing a reference is itself TriviallyCopyable (although it is not Pod, StandardLayoutType, DefaultConstructible, TriviallyDefaultConstructible, or Trivial).
Here's a few examples:
reference_wrapper
-alike internally) you can still preserve all the other properties;It's not clear what you are referring to when you discuss references.
Yes, if a particular tuple stored reference types, then it wouldn't be trivially copyable. But that's true for any type. If a type is not trivially copyable, then a type which contains that type as a subobject will also not be trivially copyable.
You cannot write a tuple which imposes trivial copyability on types that are not themselves trivially copyable.
But otherwise, it is entirely possible to write a tuple type which will be trivially copyable if all of the component types are themselves trivially copyable. That's the best guarantee you're going to get. And if you want to ensure that users never give non-trivially copyable types, you can always add a static_assert
that all of the types in the typelist are trivially copyable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With