[llvm-dev] RFC: General purpose type-safe formatting library

Tim Shen via llvm-dev llvm-dev at lists.llvm.org
Wed Oct 12 13:22:42 PDT 2016


On Wed, Oct 12, 2016 at 1:07 PM Zachary Turner <zturner at google.com> wrote:

> Couldn't you define a class FormatString like this:
>
> class FormatString {
>   template<int N>
>   constexpr FormatString(const char (&S)[N]) {
>     tokenize();
>   }
>
>   FormatString(const char *s) {}
> };
>
> Then define the format function as format(const FormatString &S, Ts
> &&...Args)
>
> The implicit conversion from string literal would go to the constexpr
> constructor which could tokenize the string at compile time, while implicit
> conversion from non-literal would be tokenized at runtime.
>

Actually it might be doable even in C++11. For example:

  template<typename Ret>
  Ret error_empty_string() {}

  constexpr char get_first_char(const char* a) {
    return *a == '\0' ? error_empty_string<char>() : a[0];
  }

  int main() {
    // { constexpr char c = get_first_char(""); }  // compile-time error
    { constexpr char c = get_first_char("a"); }  // good
    { char c = get_first_char(""); }  // runtime error handling
    { char c = get_first_char("a"); }  // good
  }


I was thinking about using static_assert, which seems hard to integrate
into only the compile-time version but not the runtime version.


>
> If that doesn't work, then like you said, you could use a UDL to force the
> checking at compile time.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20161012/2c07277e/attachment.html>


More information about the llvm-dev mailing list