Home > Software design >  It's possible to split __VA_ARGS__ and preprocess everyone and then pass them to a function
It's possible to split __VA_ARGS__ and preprocess everyone and then pass them to a function

Time:01-19

#define FORMAT_STRING(formatStr) std::format(formatStr, ##__VA_ARGS__)

int main()
{
    cout << FORMAT_STRING("{} {} ...", true, "hello") << endl;
}

this output 'true hello', but i want it output '1 hello', just like the printf("%d %s", true, "hello");. I have lots of code like this, it's hard to find and modify everyone to FORMAT_STRING("{:d} {} ...", true, "hello").

#define FMT_ARG_PRE_PROCESS(x) (std::is_same_v<decltype(x), bool> ? int(x) : (x))
#define FORMAT_STRING(formatStr) std::format(formatStr, FMT_ARG_PRE_PROCESS(##__VA_ARGS__))

this is a wrong code, because finally it looks like int(true, "hello"). I want to use FMT_ARG_PRE_PROCESS to preprocess args of FORMAT_STRING. it's possible to do similar things with other method?

IDE: vs2019 language: cpp20

CodePudding user response:

Regardless of whether it's possible or not, you could just do this with a function template:

template <typename T>
auto adjust_bool_to_int(T& t) -> T& { return t; }
auto adjust_bool_to_int(bool b) -> int { return b; }

template <typename... Args>
auto format2(format_string<Args...> fmt, Args&&... args) {
    return std::format(fmt, adjust_bool_to_int(args)...);
}
  • Related