264.md
September 5, 2022 ยท View on GitHub
Info
-
Did you know that C++20 added
__VA_OPT__for comma omission and comma deletion?
Example
#define VARIADIC(...) __VA_OPT__(__LINE__)
VARIADIC() // `empty`
VARIADIC(a) // `line` 4
VARIADIC(a, b) // `line` 5
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));
}
Solutions
#define LOG1($fmt, ...) fmt::sprintf($fmt __VA_OPT__(,) __VA_ARGS__)
#define LOG2(...) __VA_OPT__(fmt::sprintf(__VA_ARGS__))
#define LOG1($fmt, ...) fmt::sprintf($fmt __VA_OPT__(,) __VA_ARGS__)
#define LOG2(...) fmt::sprintf(__VA_ARGS__)