264.md

September 5, 2022 ยท View on GitHub

Info

Example

#define VARIADIC(...) __VA_OPT__(__LINE__)

VARIADIC()     // `empty`
VARIADIC(a)    // `line` 4
VARIADIC(a, b) // `line` 5

https://godbolt.org/z/rsj9ax7xY

Puzzle

  • Can you implement LOG1/LOG2 macros which will return formatted string and will apply __VA_OPT__?
#define LOG1($fmt, ...) // TODO
#define LOG2(...) // TODO

int main() {
    using namespace boost::ut;
    using std::string_literals::operator""s;

    expect(""s == LOG1(""));
    expect("42"s == LOG1("42"));
    expect("4"s  == LOG1("%d", 4));

    expect(""s == LOG2(""));
    expect("42"s == LOG2("42"));
    expect("4"s  == LOG2("%d", 4));
}

https://godbolt.org/z/sPTqoEdMG

Solutions

#define LOG1($fmt, ...) fmt::sprintf($fmt __VA_OPT__(,) __VA_ARGS__)
#define LOG2(...) __VA_OPT__(fmt::sprintf(__VA_ARGS__))

https://godbolt.org/z/5TM7WsMfx

#define LOG1($fmt, ...) fmt::sprintf($fmt __VA_OPT__(,) __VA_ARGS__)
#define LOG2(...) fmt::sprintf(__VA_ARGS__)

https://godbolt.org/z/135j8s5PP