Fix ADL leak of nlohmann::detail through basic_json's default base class (#5238)

This commit is contained in:
Niels Lohmann
2026-07-06 12:47:24 +02:00
committed by GitHub
parent 33edc9751c
commit acf076a677
3 changed files with 126 additions and 6 deletions
@@ -13,8 +13,6 @@
#include <nlohmann/detail/abi_macros.hpp>
NLOHMANN_JSON_NAMESPACE_BEGIN
namespace detail
{
/*!
@brief Default base class of the @ref basic_json class.
@@ -25,13 +23,27 @@ of @ref basic_json do not require complex case distinctions
@ref basic_json always has a base class.
By default, this class is used because it is empty and thus has no effect
on the behavior of @ref basic_json.
@note This class intentionally lives in namespace @ref nlohmann rather than
@ref nlohmann::detail. Every @ref basic_json specialization derives from
it (via @ref detail::json_base_class) unless a custom base class is
supplied, which makes its namespace an associated namespace of
@ref basic_json for the purpose of argument-dependent lookup (ADL). If
it lived in `nlohmann::detail`, that namespace - and with it the
library's internal `to_json`/`from_json` overloads - would leak into
ADL for any unqualified `to_json`/`from_json` call a user makes
involving a @ref basic_json argument, silently shadowing the user's own
overloads in some cases.
*/
struct json_default_base {};
namespace detail
{
template<class T>
using json_base_class = typename std::conditional <
std::is_same<T, void>::value,
json_default_base,
::nlohmann::json_default_base,
T
>::type;