作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
注意:本题使用C++20,我使用的是Visual Studio 2022 (v17.2.2)。
我想创建一个模板函数包装器,以允许我使用 std::format 样式的日志记录。包装器函数最终会做一些其他在这里不重要的非格式相关的事情。
引用下面的代码。请注意,Log1() 工作正常,但使用起来感觉笨拙。 Log2() 没问题,但使用 std::vformat() 会丢失日志格式字符串的编译时检查。
我真正想做的是Log3()。问题是 Visual Studio (v17.2.2) 不喜欢这样。
有什么方法可以让它工作(没有宏)?
#include <iostream>
#include <format>
#include <string_view>
// works fine: usage is clunky
auto Log1(std::string_view sv)
{
std::cout << sv;
}
// works, but fmt string is checked at runtime - not compile time
template<typename... Args>
auto Log2(std::string_view fmt, Args&&... args)
{
std::cout << std::vformat(fmt, std::make_format_args(args...));
}
// this doesn't work
template<typename... Args>
auto Log3(std::string_view fmt, Args&&... args)
{
std::cout << std::format(fmt, std::forward<Args>(args)...);
}
int main()
{
Log1(std::format("Hello, {}\n", "world!")); // ok - clunky
Log2("Hello, {}\n", "world!"); // ok - no compile time checking of fmt string
Log2("Hello, {:s}\n", 42); // ok - throws at runtime
Log3("Hello, {}\n", "world!"); // ERROR: doesn't compile
return 0;
}
最佳答案
你需要P2508 (我的论文)着陆,它公开了当前仅供说明的类型 std::basic-format-string<charT, Args...>
,这将允许你写:
template<typename... Args>
auto Log3(std::format_string<Args...> fmt, Args&&... args)
在那之前,您可以顽皮地使用 MSVC 实现的内部帮助程序,并了解他们可以随时随意重命名此类型。
template<typename... Args>
auto Log3(std::_Fmt_string<Args...> fmt, Args&&... args)
关于c++ - 如何用我自己的模板函数包装 std::format() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72795189/
我是一名优秀的程序员,十分优秀!