简体   繁体   中英

ambiguous << operator in Mongodb C++ driver document builder

I am trying to build a mongodb document using the v3 driver. I am using strings from an array of "char *" pointers but I keep getting an error that says the << operator is ambiguous. The exact error is:

item.cpp:105: error: ambiguous overload for 'operator<<' (operand types are

‘std::enable_if<true, bsoncxx::v_noabi::builder::stream::key_context<> >::type {aka bsoncxx::v_noabi::builder::stream::key_context<>}’ and ‘const char*’)
       << dbTypeString[dbType::IT_TYPE]

dbTypeString is an array of strings like:

const char * dbTypeString[] = {"string a", "string b"}

a simplified version of the mongo code looks like

bsoncxx::builder::stream::document doc{};

doc << dbTypeString[0] << "value string";

what is odd is that: doc << "string1" << "string2" works fine.

Any suggestions?

The error message here can be a little hard to parse, but the important parts are ambiguous overload for 'operator<<' and bsoncxx::v_noabi::builder::stream::key_context<> . The << operator is overloaded for the class bsoncxx::builder::stream::key_context (which is internally what is handling the appends to the document builder), and the compiler doesn't know which definition to use since there are multiple that could work. More specifically, there is no definition of operator<< accepting a const char * argument, but there are definitions accepting std::string and stdx::string_view , and const char * could be coerced into either of those types.

To get the code to compile, you have a couple of options. First, you can just change dbTypeString to contain std::string instead of const char * :

std::string dbTypeString[] = {"string a", "string b"}

Alternately, if you would rather keep the array as its current type, you can manually cast the const char * to a std::string , which removes the ambiguity of which overload to call:

doc << static_cast<std::string>(dbTypeString[0]) << "value string";

On a slightly tangential note, the stream builder in general can be tricky to use (especially with regards to the return type of the << operator, which has caused a fair amount of confusion in the past). I'd personally recommend using the basic builder if possible; while the API is a little less ergonomic, it doesn't suffer from the same complexity that the stream builder does, which means that in the (much rarer) occasions that you do get an error from using it improperly, debugging the issues will likely be more straightforward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM