nlohmann/json

Allow disabling problematic `operator[]` at compile time

vadz opened this issue · 1 comments

vadz commented

Description

This is yet another issue about inconsistent/unexpected behaviour of accessing elements using []. I believe that this problem is well-known to the library authors as it was discussed many times here before, so I won't describe it in details, but there is something I'd like to propose which I didn't see mentioned so far:

Would it be possible to allow predefining some symbol like JSON_NO_UNCHECKED_ACCESS to completely disable operator[] in json.hpp? I'd like to have a way to impose the use of .at() instead of [] but currently there doesn't seem anything like this, and IMHO it would be useful to all people who find the behaviour of the latter problematic.

FWIW I probably should be able to make the (simple) PR implementing this, if there is interest in it.

Reproduction steps

Compiling any code using operator[] ­— I'd like it not to compile at all if some preprocessor constant is defined.

Expected vs. actual results

operator[] can always be used currently, but I'd like to be able to disable it.

Minimal code example

No response

Error messages

No response

Compiler and operating system

This doesn't depend on the platform or compiler

Library version

3.11.3

Validation

I am hesitant to approach this, because adding yet another compile-time flag (and probably also expose it to CMake) is adding another bit of complexity to the project that needs to be documented and tested. However, if I get the feeling it is really helpful, I am open to it.