0

I'm trying to under the parse function for creating a formatter for a custom type in fmt. In their documentation (https://fmt.dev/dev/api.html) there is this line that has some sort of loop construct I haven't seen before:

auto it = ctx.begin(), end = ctx.end();
if (it != end && (*it == 'f' || *it == 'e')) presentation = *it++;

It's obviously a loop using iterators, presumably something new in C++17. What is it? Full example here: https://godbolt.org/z/fEGvaj

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
schrödinbug
  • 692
  • 9
  • 19

1 Answers1

0

The formatter::parse function takes a parse context ctx and checks if the range [ctx.begin(), ctx.end()) contains format specifiers f or e in this example.

if (it != end && (*it == 'f' || *it == 'e')) presentation = *it++;
    ^                 ^             ^
 check if the         check if the first
 range is empty       character is 'f' or 'e'

There is nothing particularly novel here, this code is compatible with C++98.

vitaut
  • 49,672
  • 25
  • 199
  • 336
  • 2
    I think I got it...the loop is external to the parse function (i.e. parse is called repeatedly until the closing brace or end of string)....holy cow... I was way over thinking it... must've been a long day or something...thanks. btw...the fmt library is awesome! – schrödinbug Jan 22 '21 at 15:59
  • is `ctx.end()` pointing to the past end of the formatting string or just the last char of the string? From the example in api doc, it says the range `[begin, end)` is the rest of the formatting string. Then for a valid string how can it happen that `it == end`. Even if you provide `{}`, the range should contain a signel char `}`, which is not empty. But if I remove the `it != end` check, it crashes, making me thing that when `{}` is used as format string, the range does not contain the `}`. – doraemon Feb 26 '23 at 16:33