Reputation: 749
I am trying to create an array with the content of a vector
using bsoncxx::builder::stream;
auto doc = document{};
doc << "foo"
<< open_array;
for (auto i : v){
doc << open_document << "bar" << i << close_document ;
}
doc << close_array;
I get the following error report:
error: no match for ‘operator<<’ (operand types are ‘bsoncxx::v0::builder::stream::document’ and ‘const bsoncxx::v0::builder::stream::open_document_type’)
doc << open_document << "bar" << i << close_document ;
Any idea on how to do it?
Upvotes: 1
Views: 439
Reputation: 661
The C++11 bson driver is actually hiding a bit more complexity under the stream style api than it at first appears.
The problem you're encountering is that there is type information encoded into the expression on each successive '<<', so from your original example you'll need to:
auto sz = 100;
// Note that we capture the return value of open_array
auto arr = doc << "foo" << open_array;
for (int32_t i=0; i < sz; i++)
arr << i;
arr << close_array;
This is because open_array creates a nested type that can accept values without keys, unlike doc, which needs key value pairs.
If you want something more inline, you can use the inline Callable facility as in:
auto sz = 100;
builder::stream::document doc;
doc << "foo" << open_array <<
[&](array_context<> arr){
for (int32_t i = 0; i < sz; i++)
arr << i;
} // Note that we don't invoke the lambda
<< close_array;
The callable facility works with things that take:
single_context - write one value in an array, or as the value part of a key value pair
key_context<> - write any number of key value pairs
array_context<> - write any number of values
See src/bsoncxx/test/bson_builder.cpp for more examples
Upvotes: 2
Reputation: 11
I have the same problem with the streaming builder.
using bsoncxx::builder::stream;
auto doc = document{};
doc << "foo"
<< open_array
<< open_document
<< "bar1" << 1
<< "bar2" << 5
<< close_document
<< close_array;
The above works, however if you want to do the following it doesn't work
doc << "foo"
<< open_array;
for (size_t i=0; i < sz; i++)
doc << i;
doc << close_array;
I get the below error. The problem is that this behavior making using the stream builder is practically useless. Perhaps its a bug or the 10gen guys are not finished with the this part of the API.
doc << closerror: no match for ‘operator<<’ (operand types are ‘bsoncxx::v0::builder::stream::document’ and ‘const bsoncxx::v0::builder::stream::open_document_type’) doc << open_document << "bar" << i << close_document ;e_array;
Upvotes: 1