Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal to use std::constructible_from in str_t to support objects with explicit conversion to string_view #1483

Closed
anders-wind opened this issue Dec 11, 2024 · 2 comments · Fixed by #1486

Comments

@anders-wind
Copy link

Hi,

Thanks for the great library!
We have some strong types which wraps std::string. These provide explicit operator std::string_view(); However if this type is a key in a json dictionary, it will have extra quotes pre/appended to it (Foo{"hello"} -> "\"hello\"").

We traced the code to:

template <opts Opts, class Key, class Value, is_context Ctx>
GLZ_ALWAYS_INLINE void write_pair_content(const Key& key, Value&& value, Ctx& ctx, auto&&... args)
{
   if constexpr (str_t<Key> || char_t<Key> || glaze_enum_t<Key> || Opts.quoted_num) {
      write<JSON>::op<Opts>(key, ctx, args...);
   }
   else {
      write<JSON>::op<opt_false<Opts, &opts::raw_string>>(quoted_t<const Key>{key}, ctx, args...);
   }
...

and the definition of str_t to

template <class T>
concept str_t = (!std::same_as<std::nullptr_t, T> && std::convertible_to<std::decay_t<T>, std::string_view>) ||
                array_char_t<T>;

Due to our class not being implicitly convertible to string_view, we end up in the else block, getting the key quoted.

Would it be possible to use the std::constructible_from<std::string_view, T> instead of the std::convertible_to in the str_t definition, as it would allow structs with explicit conversions to also function as keys without quotes?

Godbolt example of the concepts: https://godbolt.org/z/KbKa8nY7c

Might be related to #1477 but the proposed solution is a bit different.

@anders-wind anders-wind changed the title use std::constructible_from in str_t to support objects with explicit conversion to string_view Proposal to use std::constructible_from in str_t to support objects with explicit conversion to string_view Dec 11, 2024
@anders-wind anders-wind changed the title Proposal to use std::constructible_from in str_t to support objects with explicit conversion to string_view Proposal to use std::constructible_from in str_t to support objects with explicit conversion to string_view Dec 11, 2024
@stephenberry
Copy link
Owner

Thanks for suggesting this. I made the change and merged it in (#1486). Everything passes and I think it is a logical request.

@anders-wind
Copy link
Author

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants