Created
December 9, 2024 03:08
-
-
Save espresso3389/60939d7487b4c5474b888fd3a1197892 to your computer and use it in GitHub Desktop.
C++23 std::formatter implementations for WinRT classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef WINRT_FORMATTERS_H | |
#define WINRT_FORMATTERS_H | |
#include <windows.h> | |
#include <winrt/base.h> | |
#include <string> | |
#include <format> | |
template<> | |
struct std::formatter<std::wstring> : std::formatter<std::string> { | |
auto format(const std::wstring& s, std::format_context& ctx) const { | |
auto inputLength = static_cast<int>(s.size()); | |
auto size = WideCharToMultiByte(CP_UTF8, 0, s.data(), inputLength, nullptr, 0, nullptr, nullptr) + 1; | |
std::string result(size, 0); | |
WideCharToMultiByte(CP_UTF8, 0, s.data(), inputLength, result.data(), size, nullptr, nullptr); | |
result.resize(size - 1); | |
return std::formatter<std::string>::format(result, ctx); | |
} | |
}; | |
template<> | |
struct std::formatter<winrt::hstring> : std::formatter<std::string> { | |
auto format(const winrt::hstring& s, std::format_context& ctx) const { | |
auto inputLength = static_cast<int>(s.size()); | |
auto size = WideCharToMultiByte(CP_UTF8, 0, s.data(), inputLength, nullptr, 0, nullptr, nullptr) + 1; | |
std::string result(size, 0); | |
WideCharToMultiByte(CP_UTF8, 0, s.data(), inputLength, result.data(), size, nullptr, nullptr); | |
result.resize(size - 1); | |
return std::formatter<std::string>::format(result, ctx); | |
} | |
}; | |
template<> | |
struct std::formatter<winrt::hresult> : std::formatter<uint32_t> { | |
auto format(winrt::hresult result, std::format_context& ctx) const { | |
return std::format_to(ctx.out(), "0x{:08X}", result.value); | |
} | |
}; | |
#endif // WINRT_FORMATTERS_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment