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

前提是你 提交于 2020-01-07 04:58:08

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/42445029/ambiguous-operator-in-mongodb-c-driver-document-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!