Skip to content

operator T() considered harmful #958

Description

@theodelrieu

operator T() considered harmful

There's two subjects of importance that I'd like to tackle.
This is the first one, I'll open another issue quickly (hopefully).

The problem

There's been several issues in the past related to the implicit conversion operator that the library provides.
The current Readme demonstrates the following use-case:

// conversion: json -> person
ns::person p2 = j;

This will call json::operator T() with T = ns::person, so no problems here.

You'd expect the following code to always work too:

ns::person p2;
p2 = j;

And it works! Sometimes.

If ns::person has a user-defined operator=, it will break with the following message:

t.cpp: In function ‘int main(int, const char**)’:
t.cpp:14:7: error: ambiguous overload for ‘operator=’ (operand types are ‘ns::person’ and ‘nlohmann::json {aka nlohmann::basic_json<>}’)
   p2 = j;
       ^
t.cpp:6:6: note: candidate: ns::person& ns::person::operator=(int)
   ns::person& operator=(int) { return *this; }
      ^~~~~~~~
t.cpp:3:8: note: candidate: constexpr ns::person& ns::person::operator=(const ns::person&)
 struct ns::person
        ^
t.cpp:3:8: note: candidate: constexpr ns::person& ns::person::operator=(ns::person&&)

Hard to understand that error, and it's not something that can be fixed by the library.
It's triggered by the compiler before any template machinery on our side.

Now with such code:

void need_precise_measurement(Milliseconds);

// later on
json j = json::parse(config);
need_precise_measurement(j);

It can fail in two cases:

  1. Someone adds an overload for need_precise_measurement. Compiler error.
  2. Someone changes the type of the argument to Nanoseconds. Runtime error at best.

Implicit conversions

Implicit conversions make the library pleasant to use. Especially when implicitely converting to JSON.
That's because we have a templated non-explicit constructor with lots of constraints to correctly handle user types.
There's also a single type to convert to: nlohmann::json, so everything works.

However, when converting implicitely from json, it's the complete opposite. If the compiler cannot decide which type it should implicit convert the nlohmann::json value to, you get a compiler error.

And it could happen in a codebase months after writing the code, (e.g. when adding an operator= to a type).

In the end the only consistent way to convert from a json value is to call json.get<T>.

Proposed change

I propose to simply and completely remove operator T().

It will obviously break code, so it can only be done in a major version.

Of course this change cannot be adopted right away, so I propose to add a deprecation warning inside operator T(), as we did for basic_json::basic_json(std::istream&) overloads.

Then it would be reasonable to remove it in a future major version.

Activity

  1. nlohmann commented on Feb 4, 2018

    @nlohmann
    Owner

    Thanks for opening a separate issue and separating this from #951.

    I think I understand the problem, and this really may be something to tackle with 4.0.0. The question is whether there could be some middle ground, for instance a "whitelist" of supported types for which we would still have an implicit conversion. Or an extension point to let users add their desired implicit conversions. Or ...

  2. added
    state: please discuss
    on Feb 4, 2018
  3. theodelrieu commented on Feb 4, 2018

    @theodelrieu
    ContributorAuthor

    First thing I don't like about having a whitelist is that it prevents consistency. Everyone has to remember which types are supported and nobody will.

    Secondly, if types that we support get a new operator=: Ka-Boom.

    Thirdly, it doesn't solve the second example I've shown with Milliseconds and Nanoseconds.

    Now for the extension point, the best way to do that is to define another constructor or operator= to user types.

    But if users want to have an extension point for std::string, that's not possible. As I said, compilation fails before we can do anything. It will fail before the extension point mechanism gets called as well.

    I don't think we can have a middle-ground, but I might be wrong.

  4. theodelrieu commented on Feb 9, 2018

    @theodelrieu
    ContributorAuthor

    I think the customization point way can work, I'll try to experiment this weekend.

  5. theodelrieu commented on Feb 9, 2018

    @theodelrieu
    ContributorAuthor

    I had some time to experiment before lunch:

    #include <iostream>
    #include <string>
    #include <type_traits>
    
    template <typename T, typename = void> struct custom;
    
    class json;
    
    template <> struct custom<std::string> {
      static std::string convert(json const &j) { return "works"; }
    };
    
    /* Uncommenting this will break with: use of overloaded operator '=' is ambiguous
    template <> struct custom<const char*> {
      static const char* convert(json const &j) { return "works"; }
    };
    */
    
    
    class json {
    public:
      template <typename T, std::enable_if_t<sizeof(custom<T>), int> = 0>
      operator T() {
        return custom<T>::convert(*this);
      }
    };
    
    int main(int argc, char const *argv[]) {
      json j;
      std::string s;
    
      s = j;
      std::cout << s << std::endl;
    }

    But the problem remains, customization point or not, it does not solve anything...

    As for the whitelist, we already have a blacklist inside operator T(), where we explicitely disable const char*, std::initializer_list<...> etc... just to make std::string work.

    But it does not make std::vector, nor any user type with custom operator= work.
    About a macro that would conditionally disable operator T(), I find that very dangerous. Just imagine a LibA which uses a LibB, both have json as a dependency, but not with the same #define...

    If LibB implementation relies on -DJSON_DISABLE_OPERATOR_T=ON, and LibA does not, everything will break.

    My conclusion: I fear that the operator T() feature is broken by design.

  6. stale commented on Mar 11, 2018

    @stale
  7. added
    state: stale
    on Mar 11, 2018
  8. theodelrieu commented on Mar 15, 2018

    @theodelrieu
    Author
  9. removed
    state: stale
    on Mar 15, 2018
  10. stale commented on Apr 14, 2018

    @stale
  11. added
    state: stale
    on Apr 14, 2018
  12. removed
    state: stale
    on Apr 19, 2018
  13. match41 commented on Apr 24, 2018

    @match41

    I vote for the removal of the implicit converter.

    This is the same reason that C++ std::string does not convert to const char* implicitly.

  14. scinart commented on May 8, 2018

    @scinart
    Contributor

    I have a case that supports such removal. Having operator ValueType() const makes the following code very confusing.

    template <typename T>
    void f(T x)
    {
        nlohmann::json j = nlohmann::json::array();
        j.push_back(x);
        std::tuple<T> t = j;
    }
    
    int main()
    {
        f<std::string>("123"); // OK
        f<int>(123);           // throws an exception
        return 0;
    }
    

    There is nothing wrong with from_json_tuple, but rather, tuple has this strange behavior:

      template<typename... _UElements, typename
           enable_if<
    	  _TMC<_UElements...>::template
                    _MoveConstructibleTuple<_UElements...>()
                  && _TMC<_UElements...>::template
                    _ImplicitlyMoveConvertibleTuple<_UElements...>()
                  && (sizeof...(_Elements) >= 1),
        bool>::type=true>
        constexpr tuple(_UElements&&... __elements)
        : _Inherited(std::forward<_UElements>(__elements)...) { }
    
      template<typename... _UElements, typename
        enable_if<
    	  _TMC<_UElements...>::template
                    _MoveConstructibleTuple<_UElements...>()
                  && !_TMC<_UElements...>::template
                    _ImplicitlyMoveConvertibleTuple<_UElements...>()
                  && (sizeof...(_Elements) >= 1),
        bool>::type=false>
        explicit constexpr tuple(_UElements&&... __elements)
    : _Inherited(std::forward<_UElements>(__elements)...) {	}
    

    So when it is int, it requires an json->int conversion by using the implicit tuple constructor.

    Perhaps it would be something like json_cast<T>(...) that does the explicit conversion, and throws exception on cast error?

  15. stale commented on Jun 7, 2018

    @stale
  16. 69 remaining items

  17. AlexandreBossard commented on Jul 15, 2020

    @AlexandreBossard

    but do you update regularly? if you keep json at a fixed version it should be ok.

    I do, be it for feature or bug fix. And again, even if I keep json to a "stable" release, there is still a possibility a code-base change will trigger an unwanted operator T shenanigan.

  18. nlohmann commented on Jul 15, 2020

    @nlohmann
    Owner

    I understand your concerns, and I think the first step should definitely be a preprocessor switch to switch off implicit conversions. I can make a PR - is anything in addition to operator T() to be taken care of?

  19. theodelrieu commented on Jul 15, 2020

    @theodelrieu
    ContributorAuthor

    @nlohmann The PR is already there: #1559, it needs a rebase though

  20. nlohmann commented on Jul 15, 2020

    @nlohmann
    Owner

    @theodelrieu Oh, sorry, totally forgot about #1559. Can you rebase?

  21. maddanio commented on Jul 15, 2020

    @maddanio

    I would also like the list initalization to be switchable. It has similat issues.

  22. nlohmann commented on Jul 15, 2020

    @nlohmann
    Owner

    I would also like the list initalization to be switchable. It has similat issues.

    What do you mean? What do you want to switch on/off?

  23. theodelrieu commented on Jul 15, 2020

    @theodelrieu
    ContributorAuthor

    @nlohmann I just rebased

  24. linked a pull request that will close this issueFeat/explicit conversion operator #1559on Jul 22, 2020
  25. added
    solution: proposed fix
    and removed
    state: please discuss
    on Jul 23, 2020
  26. self-assigned this
    on Jul 23, 2020
  27. added this to the Release 3.8.1 milestone on Jul 23, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

release item: ✨ new featuresolution: proposed fix

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions