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

Should a UDL version of FMT_STRING be added? #1874

Closed
sth opened this issue Sep 16, 2020 · 5 comments
Closed

Should a UDL version of FMT_STRING be added? #1874

sth opened this issue Sep 16, 2020 · 5 comments

Comments

@sth
Copy link

sth commented Sep 16, 2020

Usage of the FMT_STRING() macro could be replaced by a user defined literal operator that creates a fmt::compile_string.

The advantage would be a more concise syntax and avoiding the "ugly" use of a marco: fmt::print(FMT_STRING("{}: {}"), a, b) could be written as fmt::print("{}: {}"_fmt, a, b). The disadvantage would be increased API complexity by having this additional option to create a format string and possible compatibility questions for compilers without sufficient UDL support.

I know there is a ""_format() UDL, but as I understand it that replaces the whole fmt::format() function and can't be used together with other functions like fmt::print() or fmt::format_to(). A UDL that just creates a fmt::compile_string can be used more generically in all places where a format string is expected.

It can be implemented like this:

template <typename Char, Char... CHARS>
struct udl_compile_string : fmt::compile_string {
   using char_type = Char;

   static FMT_CONSTEXPR_DECL char_type s[] = {CHARS..., '\0'};

   FMT_MAYBE_UNUSED FMT_CONSTEXPR
   operator fmt::basic_string_view<char_type>() const {
      return fmt::detail::compile_string_to_view<char_type>(s);
   }
};

template <typename Char, Char... CHARS>
FMT_CONSTEXPR udl_compile_string<Char, CHARS...> operator""_fmt() {
   return {};
}
@vitaut
Copy link
Contributor

vitaut commented Sep 16, 2020

Do you mean FMT_STRING?

@sth sth changed the title Should a UDL version of FORMAT_STR be added? Should a UDL version of FMT_STRING be added? Sep 16, 2020
@sth
Copy link
Author

sth commented Sep 16, 2020

Yes that's what I mean... I edited it.

@vitaut
Copy link
Contributor

vitaut commented Sep 16, 2020

Yes, a UDL would be better than a macro. Unfortunately it will only be implementable in a portable and efficient(ish) way in C++20.

@sarah-quinones
Copy link

here's a c++20 implementation https://godbolt.org/z/zYfErb

though this is currently only supported on gcc 10+, as far as i know

@vitaut
Copy link
Contributor

vitaut commented Nov 15, 2020

Closing in favor of #2022. We can have compile-time checks without wrapping a format string in a UDL.

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

No branches or pull requests

3 participants