How to get a variable and return multiple different datatype variable using auto in c++

65 Views Asked by At

I have to convert a rvalue to integer, boolean or string i am unable to convert it is giving the error

error: inconsistent deduction for auto return type: ‘int’ and then ‘bool’

auto convertData(const crow::json::rvalue &data) {
    std::string type = get_type_str(data.t());
    
    if(type == "Number"){
        return int(data.i());
    } else if(type == "True" || type == "False") {
        return bool(data.b());
    } 

    std::string val = data.s();
    return std::string(val);
}

Can someone please help

Edit: -

// See i am currently doing this

bsoncxx::document::value doc_value = builder
                                << "id"
                                << count
                                << "name"
                                << reqj["name"].s()
                                << "type"
                                << reqj["type"].s()
                                << "priority"
                                << priority
                                << "expense_type"
                                << reqj["expense_type"].s()
                                << "available"
                                << bool(reqj["available"].b())
                                << "life"
                                << int(reqj["life"].i())
                                << "quantity"
                                << int(reqj["quantity"].i())
                                << finalizer;
bsoncxx::document::view docview = doc_value.view();

bsoncxx::stdx::optional<mongocxx::result::insert_one> result = collection.insert_one(docview);

////////////////////////////////////////////////////////////// // Now i want to do like this

bsoncxx::builder::stream::document update_builder;
            
for (auto it = reqj.begin(); it != reqj.end(); ++it) {
    if(it->key()=="id") continue;
    update_builder << "$set" << bsoncxx::builder::stream::open_document;
    update_builder << it->key() << convertData(it->value());
    update_builder << bsoncxx::builder::stream::close_document;
}

bsoncxx::document::value update = update_builder << finalizer;

bsoncxx::stdx::optional<mongocxx::result::insert_one> result = collection.insert_one(update_builder());

// The collection.insert_one updates the data in database
1

There are 1 best solutions below

3
463035818_is_not_an_ai On

auto return type cannot do that. The type of the returned value must be known statically. You could consider to return a std::variant<std::string,int>. However, I suspect that crow::json::rvalue is already some kind of variant.

You could make the function a template:

template <typename T>
T getAs(const crow::json::rvalue &data);

Such that the caller specifies the type:

std::string s = getAs<std::string>(x);

If it is only 2 types, I would rather recommend to write two overloads: getAsString and getAsInt though.