nlohmann / json

JSON for Modern C++
https://json.nlohmann.me
MIT License
41.46k stars 6.59k forks source link

to_bson member function ignores BinaryType template parameter #4072

Open danielalves opened 1 year ago

danielalves commented 1 year ago

Description

Currrently to_bson is implemented like this:

static std::vector<std::uint8_t> to_bson(const basic_json& j)
{
    std::vector<std::uint8_t> result;
    to_bson(j, result);
    return result;
}

which ignores the BinaryType template parameter received by basic_json.

It should use the BinaryType instead:

static BinaryType to_bson(const basic_json& j)
{
    BinaryType result;
    to_bson(j, result);
    return result;
}

Reproduction steps

#include <type_traits>

typedef nlohmann::basic_json<
    std::map,
    std::vector,
    std::string,
    bool,
    std::int64_t,
    std::uint64_t,
    double,
    std::allocator,
    nlohmann::adl_serializer,
    std::vector<std::byte>,
    void
> CustomJson;

void test() {
    CustomJson oauthDataJson = {
        {"key", "value"}
    };
    auto result = CustomJson::to_bson(oauthDataJson);

    // This won't compile because static_assert will fail 
    static_assert(std::is_same_v<CustomJson::binary_t, decltype(result)>);
}

Expected vs. actual results

Minimal code example

// Same as `Reproduction Steps`

#include <type_traits>

typedef nlohmann::basic_json<
    std::map,
    std::vector,
    std::string,
    bool,
    std::int64_t,
    std::uint64_t,
    double,
    std::allocator,
    nlohmann::adl_serializer,
    std::vector<std::byte>,
    void
> CustomJson;

void test() {
    CustomJson oauthDataJson = {
        {"key", "value"}
    };
    auto result = CustomJson::to_bson(oauthDataJson);

    // This won't compile because static_assert will fail 
    static_assert(std::is_same_v<CustomJson::binary_t, decltype(result)>);
}

Error messages

No response

Compiler and operating system

all

Library version

3.11.2

Validation