我有两个广泛相关的问题。
我想要创建一个函数,将参数转发到fmt::format
(以后当支持增加时也可以转发到std::format
)。类似于这样:
#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;
}
使用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
并使用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
在图书馆中(core.h)声明了如下内容:template <typename... T>
auto format(format_string<T...> fmt, T&&... args) -> std::string {
// ...
}
问题在于cppreference指示第一个参数的类型是未指定的。因此,
- 我该如何创建一个类似于
my_print
的函数,将参数传递给fmt::format
,同时捕获相同类型的错误?是否有一种更普遍的方法来为任何类型的函数执行此操作? - 我该如何推断出像
std::format
这样的函数参数的类型?
更具体地说,我想创建一个条件调用std::format
的函数,如果不需要字符串,则完全避免格式化。如果您知道更好的方法,请留言,我将非常感激。但是,我关于如何解决通用问题的问题仍然存在。
my_print
的宏。 - NathanOliverfmt::format
不是constexpr
,所以my_print
也不能是。 - Jarod42fmt
的作者在这里给出了真正的答案,这个答案和Joseph在这里给出的答案是一样的。 - underscore_d