I have two broadly related questions.
I want to make a function that forwards the arguments to fmt::format
(and later to std::format
, when the support increases). Something like this:
#include <iostream>
#include <fmt/core.h>
constexpr auto my_print(auto&& fmt, auto&&... args) {
// Error here!
// ~~~~~~~~v~~~~~~~~
return fmt::format(fmt, args...);
}
int main() {
std::cout << my_print("{}", 42) << std::endl;
}
Tested with gcc 11.1.0:
In instantiation of ‘constexpr auto my_print(auto:11&&, auto:12&& ...) [with auto:11 = const char (&)[3]; auto:12 = {int}]’:
error: ‘fmt’ is not a constant expression
And tested with clang 12.0.1:
error: call to consteval function 'fmt::basic_format_string<char, int &>::basic_format_string<char [3], 0>' is not a constant expression
In the library (core.h) it's declared something like this:
template <typename... T>
auto format(format_string<T...> fmt, T&&... args) -> std::string {
// ...
}
The problem is that cppreference indicates that the type of the first parameter is unspecified. So
- How can I make a function like
my_print
that passes the arguments tofmt::format
and still catches the same kind of errors? Is there a more general way to do this for any kind of function? - How can I infer the type of a parameter of a function like
std::format
?
For more context, I want to make a function that calls to std::format
conditionally, avoiding the formatting at all if the string won't be needed. If you know a better way to make this leave a comment, I'll be very greatful. However, my question about how to solve the general problem still stands.
my_print
. – Chloralfmt::format
is notconstexpr
, somy_print
cannot be neither. – Shoalfmt
gave the real answer, which is the same that Joseph did here. – Lindsay