如何使用 <format> header
How to use the <format> header
在相关问题中 ("std::string formatting like sprintf") I learned about this awesome new C++20 header <format>.
然而,there seems to be no supporting compiler。这是正确的还是有办法使用它?
我正在使用带有 -std=c++2a
标志的 g++ 9.3,但无法识别库 <format>
。
#include <format> // fatal error: format: No such file or directory
#include <iostream>
int main(){
std::cout << std::format("Hello {}!", "World");
}
g++-9 test.cpp -o test -std=c++2a
使用libfmt
。 <format>
header 本质上是一个标准化的 libfmt(如果我没记错的话,删除了一些小功能)。
debian/ubuntu 上有一个 libfmt-dev
包可用。
我目前使用此 header 替代 format
header:
#include <fmt/core.h>
#include <fmt/ranges.h>
namespace std
{
template<typename... Args> \
inline auto format(Args&&... args) -> decltype(fmt::v7::format(std::forward<Args>(args)...)) \
{ \
return fmt::v7::format(std::forward<Args>(args)...); \
}
}
这是实验性的:我不知道 std::format
和 fmt::format
之间的确切区别。
生活充满惊喜
在相关问题中 ("std::string formatting like sprintf") I learned about this awesome new C++20 header <format>.
然而,there seems to be no supporting compiler。这是正确的还是有办法使用它?
我正在使用带有 -std=c++2a
标志的 g++ 9.3,但无法识别库 <format>
。
#include <format> // fatal error: format: No such file or directory
#include <iostream>
int main(){
std::cout << std::format("Hello {}!", "World");
}
g++-9 test.cpp -o test -std=c++2a
使用libfmt
。 <format>
header 本质上是一个标准化的 libfmt(如果我没记错的话,删除了一些小功能)。
debian/ubuntu 上有一个 libfmt-dev
包可用。
我目前使用此 header 替代 format
header:
#include <fmt/core.h>
#include <fmt/ranges.h>
namespace std
{
template<typename... Args> \
inline auto format(Args&&... args) -> decltype(fmt::v7::format(std::forward<Args>(args)...)) \
{ \
return fmt::v7::format(std::forward<Args>(args)...); \
}
}
这是实验性的:我不知道 std::format
和 fmt::format
之间的确切区别。
生活充满惊喜