Skip to content

Add a customization point for user-defined types #328

Closed

Description

@theodelrieu

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:

// library code
template <typename UserDefinedType>
struct json_traits;

// user code
template <>
struct json_traits<MyType>
{
  static basic_json convert(MyType const& val)
  {
    return {{"first_row", val.first_row}, {"some_value", 42}};
  }
};

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?

Activity

  1. gregmarr commented on Oct 12, 2016

    @gregmarr
    Contributor

    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.

  2. nlohmann commented on Oct 12, 2016

    @nlohmann
    Owner

    This issue is related to #298 and #280.

  3. nlohmann commented on Oct 12, 2016

    @nlohmann
    Owner

    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?

  4. gregmarr commented on Oct 12, 2016

    @gregmarr
    Contributor

    It's all static functions, the class is never instantiated.

  5. nlohmann commented on Oct 12, 2016

    @nlohmann
    Owner

    I still do not understand what to add to the basic_json class.

  6. gregmarr commented on Oct 12, 2016

    @gregmarr
    Contributor

    Maybe something like this:

    template<typename T> basic_json(T&& val) :
        basic_json(json_traits<T>::convert(std::forward<T>(val)))
    {
        assert_invariant();
    }
    

    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.)

  7. gregmarr commented on Oct 12, 2016

    @gregmarr
    Contributor

    Yeah, this is basically what @gnzlbg and @d-frey described in #298

  8. theodelrieu commented on Oct 12, 2016

    @theodelrieu
    ContributorAuthor

    Indeed, looking at taocpp value.hh and traits.hh can help to understand the idea

  9. added a commit that references this issue on Oct 12, 2016
  10. theodelrieu commented on Oct 12, 2016

    @theodelrieu
    ContributorAuthor

    I started a POC on my fork. (I didn't modify the re2c file, but I will !)

  11. theodelrieu commented on Oct 13, 2016

    @theodelrieu
    ContributorAuthor

    There is an issue with that ctor however...

    // not equality-comparable
    struct S{};
    
    int main()
    {
    // 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

  12. gnzlbg commented on Oct 13, 2016

    @gnzlbg

    (json_traits::convert(std::forward(val)))

    What is the advantage of json_traits<T>::convert over a simpler json_convert free function that is found via ADL ?

  13. theodelrieu commented on Oct 13, 2016

    @theodelrieu
    ContributorAuthor

    @gnzlbg one thing that comes to mind is the ability to partially specialize the struct

    We could imagine a specialization for boost::optional for example

    template <typename T>
    struct json_traits<boost::optional<T>>
    {
       // ...
    };
  14. gnzlbg commented on Oct 13, 2016

    @gnzlbg

    What's wrong with just using overloading?

    template <typename T>
    auto json_convert(boost::optional<T> const&) -> basic_json { ... }

    (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):

    template <typename Optional, CONCEPT_REQUIRES_(OptionalLike<Optional>{})>
    auto json_convert(Optional const&) -> basic_json { ... }

    (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).

  15. 7 remaining items

  16. theodelrieu commented on Oct 17, 2016

    @theodelrieu
    ContributorAuthor

    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.

  17. gnzlbg commented on Oct 17, 2016

    @gnzlbg

    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:

    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.

    —
    You are receiving this because you were mentioned.
    Reply to this email directly, view it on GitHub
    #328 (comment), or mute
    the thread
    https://github.com/notifications/unsubscribe-auth/AA3Nppi9q2mgW4UExUy_4l8Q_HnYCbBrks5q01I_gaJpZM4KU7Jf
    .

  18. theodelrieu commented on Oct 17, 2016

    @theodelrieu
    ContributorAuthor

    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

  19. theodelrieu commented on Oct 18, 2016

    @theodelrieu
    ContributorAuthor

    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.

  20. gnzlbg commented on Oct 19, 2016

    @gnzlbg

    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.

  21. gnzlbg commented on Oct 19, 2016

    @gnzlbg

    Some things:

    • 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.

  22. theodelrieu commented on Oct 19, 2016

    @theodelrieu
    ContributorAuthor

    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!

  23. d-frey commented on Oct 19, 2016

    @d-frey
    Contributor

    @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... ;)

  24. gnzlbg commented on Oct 19, 2016

    @gnzlbg

    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, typename JSON>
    void to_json(T[N] const&, JSON&);

    or by specializing a trait class:

    template<typename T, std::size_t N> 
    struct json_traits<T[N]> { ... };`

    But if you "decay" the types before using ADL or the trait class, the following will be try to be picked instead:

    template <typename T, typename JSON>
    void to_json(T*, JSON&);
    
    template<typename T> 
    struct json_traits<T*> { ... };`

    which will fail to pattern-match because T* != T[N] for the trait class, and because T* cannot be converted to T[N] for the free functions.

    So what @theodelrieu actually wants is typically called uncvref_t (range-v3, STL2 which also has __uncvref, ...):

    template <typename T>
    using uncvref_t = std::remove_cv_t<std::remove_reference_t<T>>;

    Sadly, this is not in the standard library yet, but while std::decay_t almost 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:

    template <typename T> struct json_traits;
    template <typename T> struct json_traits<const T> : json_traits<T> { ... }
    template <typename T> struct json_traits<volatile T> : json_traits<T> { ... }
    template <typename T> struct json_traits<const volatile T> : json_traits<T> { ... }

    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.

  25. self-assigned this
    on Jan 27, 2017
  26. added this to the Release 2.1.0 milestone on Jan 27, 2017
  27. nlohmann commented on Jan 27, 2017

    @nlohmann
    Owner

    This feature is implemented, see #435.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions