You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Add a customization point for user-defined types #328
Hi, I think it would be a cool addition to the library if there was a way to specify a conversion method, from a type to basic_json, which would be called by the lib.
Here a sample code of the behaviour I'm thinking about:
There could also be a conversion method when get is called
auto obj = json::parse(buffer);
auto val = obj["user_defined_type_value"].get<MyType>();
These are just thoughts for now, but that would remove a LOT of boilerplate in my code.
Plus, this would add some compile-time checks (if the struct is not defined for example)
What's your opinion on that?
That would be cool. I created to_json and from_json functions for a lot of my types, and use to_json/from_json exclusively even for types it already supports. Making them work automatically out of the box would be even cooler.
I have not understood the role of json_traits completely. Shouldn't there be a constructor in the basic_json class for the json_traits template? Would this constructor then be usable for any class that is specialized by json_traits?
There might also need to be some enable_if code to keep the current constructors working, or maybe the current constructors become specializations of the json_traits class instead. (Though that using specializations part might get into cyclical dependencies.)
// not equality-comparablestructS{};
intmain()
{
// this will call operator==(basic_json, basic_json) if json_traits<S> was specialized// and it will do so for every operator defined for basic_json ...S() == S();
}
I'm looking for a way to bypass this, without making the constructor explicit
(note: json could include these overloads in some separate header, but they would add a dependency on boost::optional).
I find that for most people free functions and overloading are easier to understand than trait classes and partial template specialization. One thing overloading allows is to implement json_convert once for all Optional-like types (given an OptionalLike concept that requires .value() and explicit operator bool) using enable_if (behind a CONCEPT_REQUIRES_ macro like in, e.g., range-v3):
(note: since boost/std/...::optional is not directly used here, json could actually add this overload without introducing a dependency on any of these libraries).
EDIT: Doing the same with partial template specialization is a bit "more hacky" since it would require not only requires and an OptionalLike concept but also void_t (which while simple to write, is a bit harder to understand why it works).
Hi, I've committed a first version with a json_traits struct. I added a constructor, a get_impl overload, and a unit-constructors3.cpp file in the test suite.
I tried to implement the customization-point design proposed by Eric Niebler, unfortunately variable templates are not supported in VS 2015, so I decided to begin with the traits struct.
I'm sure I missed quite a lot of things, so I'm looking for your feedbacks.
Hi, I've committed a first version theodelrieu@a2a8fec
with a json_traits struct. I added a constructor, a get_impl overload,
and a unit-constructors3.cpp file in the test suite.
I tried to implement the customization-point design proposed by Eric
Niebler, unfortunately variable templates are not supported in VS 2015, so
I decided to begin with the traits struct.
I'm sure I missed quite a lot of things, so I'm looking for your feedbacks.
Hi, I've implemented the from_json/to_json free function support on my fork.
I'd really appreciate all your feedbacks on the diff I linked. (especially you @gnzlbg, since you're more aware than me about the subject of ADL free-function style!).
I wrote comments questioning the design choices I've made in json.hpp.
I also added some stuff that might be out of this feature's scope, that I should add in a different PR (e.g. alias templates)
EDIT: Should I start a PR now? This would make it easier to review/comment.
I think it is easier to give feedback if you open a PR, just make it clear to @nlohmann that the work is not finished yet and that it should not be merged yet.
you probably don't want to use remove_cv/remove_reference<T> independently from each other, but rather always use remove_cv<remove_reference<T>>. This is typically called uncvref_t, e.g., see range-v3.
design: you do a lot of "if has json_traits do this, else if from_json/to_json are valid overloads, do that. I think this is too complicated. In my opinion it is easier if:
JSONSerialization is a template parameter of basic_json
you create a json_serialization_adl "trait", that has from/to static members that call from_/to_json free functions via ADL.
you use that as the default template argument for the JSONSerialization template parameter.
That is, to serialize something in basic_json you only use JSONSerialization::from/to and be done with it.
If the user doesn't care, ADL will trigger and do "the easy thing".
If the user does care like @d-frey they can write their own trait class that does whatever they want and pass it as a template parameter to, e.g., have different basic_json types that serialize the same objects to and from json in different ways.
@theodelrieu Instead of std::remove_cv_t<std::remove_reference_t<...>> you probably want to use std::decay_t<...>. It does what remove_cv+remove_reference does and more, like taking care of turning const char(&)[N] into const char* - which is what you most likely want. It's almost as if it was made for this kind of use-case... ;)
like taking care of turning const char(&)[N] into const char* - which is what you most likely want.
As @d-frey says, std::decay_t "decays" types like when passed by value to functions arguments (which does array to pointer conversion). However, where @theodelrieu uses remove_cv<remove_reference<T>> he actually doesn't want the arguments to decay like as when passed to functions because that would break both ADL and the trait system for serialization.
An user (or probably, this library) can implement to_/from_json for C-arrays using ADL:
template <typename T, std::size_t N, typenameJSON>
voidto_json(T[N] const&, JSON&);
Sadly, this is not in the standard library yet, but while std::decay_talmost does what you want, it breaks in subtle ways. The only safe situation in which one should really use std::decay_t is when one actually really wants to perform decaying of values as when passed to functions as arguments. This happens, for example, when implementing something that calls functions, like std::bind, std::mem_fn, std::result_of, std::invoke... and such. For picking specializations in trait classes independently of reference and const/volatile qualifiers, uncvref_t is what you want.
If you want the implementation of the "default" json_traits to be 200% generic, you actually want to use std::remove_reference_t only, and specialize your trait class like e.g. libc++ does for tuple_size:
If a user just specializes json_traits for his own T, this will work with a cv qualified T as well. But if a user wants to have different types of json serialization for T than for const volatile T, this allows specializations for cv-qualified types as well. If you would use uncvref_t, cv-qualified specializations would never pattern-match successfully (because uncvref_t removes the cv qualifiers).
Buuuut... I don't think we should support different types of serialization depending on cv-qualifiers, at least not until somebody complains that they need them.
Activity
gregmarr commentedon Oct 12, 2016
That would be cool. I created to_json and from_json functions for a lot of my types, and use to_json/from_json exclusively even for types it already supports. Making them work automatically out of the box would be even cooler.
nlohmann commentedon Oct 12, 2016
This issue is related to #298 and #280.
nlohmann commentedon Oct 12, 2016
I have not understood the role of
json_traitscompletely. Shouldn't there be a constructor in thebasic_jsonclass for thejson_traitstemplate? Would this constructor then be usable for any class that is specialized byjson_traits?gregmarr commentedon Oct 12, 2016
It's all static functions, the class is never instantiated.
nlohmann commentedon Oct 12, 2016
I still do not understand what to add to the
basic_jsonclass.gregmarr commentedon Oct 12, 2016
Maybe something like this:
There might also need to be some enable_if code to keep the current constructors working, or maybe the current constructors become specializations of the json_traits class instead. (Though that using specializations part might get into cyclical dependencies.)
gregmarr commentedon Oct 12, 2016
Yeah, this is basically what @gnzlbg and @d-frey described in #298
theodelrieu commentedon Oct 12, 2016
Indeed, looking at taocpp value.hh and traits.hh can help to understand the idea
add poc for issue nlohmann#328
theodelrieu commentedon Oct 12, 2016
I started a POC on my fork. (I didn't modify the re2c file, but I will !)
theodelrieu commentedon Oct 13, 2016
There is an issue with that ctor however...
I'm looking for a way to bypass this, without making the constructor explicit
gnzlbg commentedon Oct 13, 2016
What is the advantage of
json_traits<T>::convertover a simplerjson_convertfree function that is found via ADL ?theodelrieu commentedon Oct 13, 2016
@gnzlbg one thing that comes to mind is the ability to partially specialize the struct
We could imagine a specialization for
boost::optionalfor examplegnzlbg commentedon Oct 13, 2016
What's wrong with just using overloading?
(note:
jsoncould include these overloads in some separate header, but they would add a dependency onboost::optional).I find that for most people free functions and overloading are easier to understand than trait classes and partial template specialization. One thing overloading allows is to implement
json_convertonce for all Optional-like types (given an OptionalLike concept that requires.value()andexplicit operator bool) usingenable_if(behind aCONCEPT_REQUIRES_macro like in, e.g., range-v3):(note: since
boost/std/...::optionalis not directly used here,jsoncould actually add this overload without introducing a dependency on any of these libraries).EDIT: Doing the same with partial template specialization is a bit "more hacky" since it would require not only
requiresand anOptionalLikeconcept but alsovoid_t(which while simple to write, is a bit harder to understand why it works).7 remaining items
theodelrieu commentedon Oct 17, 2016
Hi, I've committed a first version with a
json_traitsstruct. I added a constructor, aget_imploverload, and aunit-constructors3.cppfile in the test suite.I tried to implement the customization-point design proposed by Eric Niebler, unfortunately variable templates are not supported in VS 2015, so I decided to begin with the traits struct.
I'm sure I missed quite a lot of things, so I'm looking for your feedbacks.
gnzlbg commentedon Oct 17, 2016
Range-v3 implementation does not require variable templates (see
include/range/v3/utility/static_const.hpp).
On Monday, 17 October 2016, Théo DELRIEU notifications@github.com wrote:
theodelrieu commentedon Oct 17, 2016
I see, I tried to use the example code from the paper, but the code you linked compiles on VS2015. I will try to implement that too
theodelrieu commentedon Oct 18, 2016
Hi, I've implemented the
from_json/to_jsonfree function support on my fork.I'd really appreciate all your feedbacks on the diff I linked. (especially you @gnzlbg, since you're more aware than me about the subject of ADL free-function style!).
I wrote comments questioning the design choices I've made in
json.hpp.I also added some stuff that might be out of this feature's scope, that I should add in a different PR (e.g. alias templates)
EDIT: Should I start a PR now? This would make it easier to review/comment.
gnzlbg commentedon Oct 19, 2016
I think it is easier to give feedback if you open a PR, just make it clear to @nlohmann that the work is not finished yet and that it should not be merged yet.
gnzlbg commentedon Oct 19, 2016
Some things:
remove_cv/remove_reference<T>independently from each other, but rather always useremove_cv<remove_reference<T>>. This is typically calleduncvref_t, e.g., see range-v3.json_traitsdo this, else iffrom_json/to_jsonare valid overloads, do that. I think this is too complicated. In my opinion it is easier if:JSONSerializationis a template parameter ofbasic_jsonjson_serialization_adl"trait", that hasfrom/tostatic members that callfrom_/to_jsonfree functions via ADL.JSONSerializationtemplate parameter.That is, to serialize something in
basic_jsonyou only useJSONSerialization::from/toand be done with it.If the user doesn't care, ADL will trigger and do "the easy thing".
If the user does care like @d-frey they can write their own trait class that does whatever they want and pass it as a template parameter to, e.g., have different
basic_jsontypes that serialize the same objects to and from json in different ways.theodelrieu commentedon Oct 19, 2016
I opened a PR.
At first I found the template-argument design a bit annoying to people specializing the traits struct.
But it avoids some confusion, and lets people control serialization. I'll implement that and come back to you, thanks for the feedback!
d-frey commentedon Oct 19, 2016
@theodelrieu Instead of
std::remove_cv_t<std::remove_reference_t<...>>you probably want to usestd::decay_t<...>. It does whatremove_cv+remove_referencedoes and more, like taking care of turningconst char(&)[N]intoconst char*- which is what you most likely want. It's almost as if it was made for this kind of use-case... ;)gnzlbg commentedon Oct 19, 2016
As @d-frey says,
std::decay_t"decays" types like when passed by value to functions arguments (which does array to pointer conversion). However, where @theodelrieu usesremove_cv<remove_reference<T>>he actually doesn't want the arguments to decay like as when passed to functions because that would break both ADL and the trait system for serialization.An user (or probably, this library) can implement
to_/from_jsonfor C-arrays using ADL:or by specializing a trait class:
But if you "decay" the types before using ADL or the trait class, the following will be try to be picked instead:
which will fail to pattern-match because
T* != T[N]for the trait class, and becauseT*cannot be converted toT[N]for the free functions.So what @theodelrieu actually wants is typically called
uncvref_t(range-v3, STL2 which also has__uncvref, ...):Sadly, this is not in the standard library yet, but while
std::decay_talmost does what you want, it breaks in subtle ways. The only safe situation in which one should really usestd::decay_tis when one actually really wants to perform decaying of values as when passed to functions as arguments. This happens, for example, when implementing something that calls functions, likestd::bind,std::mem_fn,std::result_of,std::invoke... and such. For picking specializations in trait classes independently of reference andconst/volatilequalifiers,uncvref_tis what you want.If you want the implementation of the "default"
json_traitsto be 200% generic, you actually want to usestd::remove_reference_tonly, and specialize your trait class like e.g. libc++ does fortuple_size:If a user just specializes
json_traitsfor his ownT, this will work with a cv qualifiedTas well. But if a user wants to have different types of json serialization forTthan forconst volatile T, this allows specializations for cv-qualified types as well. If you would useuncvref_t, cv-qualified specializations would never pattern-match successfully (becauseuncvref_tremoves the cv qualifiers).Buuuut... I don't think we should support different types of serialization depending on cv-qualifiers, at least not until somebody complains that they need them.
nlohmann commentedon Jan 27, 2017
This feature is implemented, see #435.