[SERVER-54358] BSONElement should support destructuring assignment using tuple protocol Created: 05/Feb/21  Updated: 29/Oct/23  Resolved: 29/Mar/22

Status: Closed
Project: Core Server
Component/s: Internal Code
Affects Version/s: None
Fix Version/s: 6.0.0-rc0

Type: Improvement Priority: Major - P3
Reporter: Mathias Stearn Assignee: Mathias Stearn
Resolution: Fixed Votes: 1
Labels: mathias-sa-triage
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Backwards Compatibility: Fully Compatible
Participants:

 Description   

Then we could write for (auto&& [k, v] : someBsonObj) like you can for other kv-pair maps in C++. It is slightly weird that the second element of a BSONElement is the element itself, but I think it would work nicely in practice.



 Comments   
Comment by Githook User [ 29/Mar/22 ]

Author:

{'name': 'Mathias Stearn', 'email': 'redbeard0531@gmail.com', 'username': 'RedBeard0531'}

Message: SERVER-54358 enable for (auto [name, elem] : someBsonObj)

{...}

Branch: master
https://github.com/mongodb/mongo/commit/07ba0f5fb79b855f9abc260ac35126c30b362e29

Comment by Mathias Stearn [ 05/Feb/21 ]

This code seems to do the trick. It may be better to use decltype(auto) as the return type from get() to avoid making a copy when doing structured binding.

namespace std {
template <>
struct tuple_size<mongo::BSONElement> : std::integral_constant<size_t, 2> {};
template <size_t I>
struct tuple_element<I, mongo::BSONElement>
    : std::tuple_element<I, std::pair<mongo::StringData, mongo::BSONElement>> {};
}  // namespace std
 
namespace mongo {
template <size_t I>
auto get(const BSONElement& elem) {
    static_assert(I <= 1);
    if constexpr (I == 0) {
        return elem.fieldNameStringData();
    } else if constexpr (I == 1) {
        return elem;
    }
}
}  // namespace mongo

Generated at Thu Feb 08 05:33:19 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.