41 points · by eklitzke · 5y ago · 30 comments
I wrote the tuple implementation which was included in g++ for a while (technically libstdc++) -- it used some reasonably awful preprocessor to generate the different arities of tuple.
Once you get to C++11, you at least didn't need to do it with pre-processor magic.
At some point there were multiple lambda libraries before we got language support for it.
Use a combination of std::forward_as_tuple [1] and std::tuple_cat [2] to successively construct each element one-by-one and in place.
If you have a specific use case I could show you how to use them.
[1] https://en.cppreference.com/w/cpp/utility/tuple/forward_as_t...
[2] https://en.cppreference.com/w/cpp/utility/tuple/tuple_cat
But I think the same problem would apply to any class: you can't construct an object without constructing its fields. The workaround would be to wrap each field in a union so that it can be trivially default constructed, then use placement new. But then where would you track how many fields have been initialized so far? In a separate iterator object? What would the tuple's destructor do?
> Chromium targets C++14; C++17 support is not expected before mid-2021.
[1]: <https://chromium.googlesource.com/chromium/src/+/master/styl...>
To wit, I've literally never used vector<any>, but tuple quite a lot(though often just because it's convenient for some metaprogramming hacks).
I'm getting the sense you have no idea what's being talked about here, and what tuple is actually for. Instead of saying anything at all you give me two links, one of which is a 30 minute read(are you serious?) that seems to have little to do with the topic, and the other is literally just an explanation of what std::any is(really, are you serious?).
I'll try to be at least somewhat charitable, and explain where I'm coming from. Tuple is a statically-typed container, that is useful in a generic context - which, crucially, doesn't mean polymorphic at runtime! - because its members' types can be inspected at compile time, unlike a struct. This makes it useful for implementing all sorts of template magic. You can also use it like a anonymous struct, for a quick-and-dirty way to return multiple values from a function, though a struct is often better.
std::any, on the other hand, is, uh, not like that at all, whether it is in a vector or not. It holds a single value that is polymorphic at runtime, by erasing its type, which has nothing to do with tuples, and helps with none of the above.