[C++20] std::format 사용해보기
std::string을 사용하면서 printf처럼 formatting 기능을 사용하고 싶었다.
혹시 새로운 기능이 없을까 하고 검색해보니 c++20에 std::format이라는 기능이 추가되었다고 한다.
std::format은 아래와 같이 std::string_view를 인자로 받는다.
template<class... Args>
string format(string_view fmt, const Args&... args);
string_view이기 때문에 그냥 const char*를 넘겨도 된다.
기본 사용방법은 아래와 같다.
std::format("{} {}!", "Hello", "world"); // Hello world!
{} 위치에 배치된다고 보면 된다.
{} 이곳에 들어갈 여러가지 기능들은 너무 많아서 링크로 대신한다.
필요할때 마다 검색해서 사용해봐야 될 것 같다.
https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification
std::formatter - cppreference.com
template struct formatter; (since C++20) The enabled specializations of formatter define formatting rules for a given type. Enabled specializations meet the Formatter requirements. In particular, they define callables parse and format. For all types T and
en.cppreference.com
format을 사용하기 위해서는 Visual Studio 2019를 16.10 버전 이상으로 올려야 하고
C++ 버전은 latest로 변경해야 한다.
Vector3를 String으로 변경하는 간단한 코드를 예제로 남기고 마무리하면 될 것 같다.
class Vector3
{
public:
float x_, y_, z_;
public:
std::string toString()
{
return std::format("( {:.2f}, {:.2f}, {:.2f} )", x_, y_, z_);
}
};