3 ms·
Great to hear that you made good experiences with user-defined allocators. It would be great if you could provide a pointer to an example, because we always fal
by nlohmann 5y ago
Great to hear that you made good experiences with user-defined allocators. It would be great if you could provide a pointer to an example, because we always fall short in testing the allocator usage. So if you had a small example, you could really improve the status quo :)
- qalmakka 5y agoThanks a lot to you for writing such an awesome library! :) This is briefly how I use C++ Allocators with the ESP32 and Nlohmann/JSON (GCC8, C++17 mode): I have a series of "extmem" headers which define aliases for STL containers which use my allocator (ext::allocator). The allocator is a simple allocator that just uses IDF's heap_caps_malloc() to allocate memory on the SPIRAM of the ESP-WROVER SoC. I then define in <extmem/json.hpp>: namespace ext { using json = nlohmann::basic_json<std::map, std::vector, ext::string, bool, long long, unsigned long long, double, ext::allocator, nlohmann::adl_serializer>; } where `ext::string` is just `std::basic_string<char, std::char_traits<char>, ext::allocator<char>>`. In order to be able to define generic from/to_json functions in an ergonomic way, I had to reexport the following internal macros in a separate header: #define JSON_TEMPLATE_PARAMS \ template<typename, typename, typename...> class ObjectType, \ template<typename, typename...> class ArrayType, \ class StringType, class BooleanType, class NumberIntegerType, \ class NumberUnsignedType, class NumberFloatType, \ template<typename> class AllocatorType, \ template<typename, typename = void> class JSONSerializer #define JSON_TEMPLATE template<JSON_TEMPLATE_PARAMS> #define GENERIC_JSON \ nlohmann::basic_json<ObjectType, ArrayType, StringType, BooleanType, \ NumberIntegerType, NumberUnsignedType, NumberFloatType, \ AllocatorType, JSONSerializer> I am now able to just write stuff like the following: JSON_TEMPLATE inline void from_json(const GENERIC_JSON &j, my_type &t) { // ... } JSON_TEMPLATE inline void to_json(GENERIC_JSON &j, const my_type &t) { // ... } And it works fine with both nlohmann::json and ext::json. In the rest of the code, everything stays the same; I simply use ext::json (and catch const ext::json::exception&) as if it were it's default version, and it works great. FYI, I'm currently using nlohmann/json v.3.9.1.