Skip to content

Instantly share code, notes, and snippets.

@espresso3389
Created December 9, 2024 03:08
Show Gist options
  • Save espresso3389/60939d7487b4c5474b888fd3a1197892 to your computer and use it in GitHub Desktop.
Save espresso3389/60939d7487b4c5474b888fd3a1197892 to your computer and use it in GitHub Desktop.
C++23 std::formatter implementations for WinRT classes
#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