std::format for std::wstring GCC 的自定义格式化程序

问题描述 投票:0回答:1

我正在尝试为

std::format
制作一个格式化程序,它将需要
std::wstring
并将其格式化为
std::string
。我的想法是用“
?
”替换所有不可转换的字符。

#include <format>
#include <string>
#include <iostream>

template<>
struct std::formatter<std::wstring> : public std::formatter<std::string> {

    template<typename ParsContext>
    constexpr auto parse(ParsContext& ctx) {
        return std::begin(ctx);
    }

    template<typename FormatContext>
    auto format(const std::wstring &obj, FormatContext &ctx) const {
        std::string result{};
        for(const auto & wch : obj){
            if(wch < 0x80){
                std::format_to(std::back_inserter(result), "{}", static_cast<char>(wch));
            }else{
                std::format_to(std::back_inserter(result), "?");
            }
        }
        return std::formatter<std::string>::format(result, ctx);
    }
};

int main(){
    std::wstring test{L"Hello wide world.こんにちは、안녕하세요!\n"};
    std::cout << std::format("{}", test); 
}

导致以下编译器错误:(小样本,编译器资源管理器中出现完整错误)

/opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/format:3029:19:错误:没有匹配的函数用于调用“std::basic_string_view::basic_string_view()” 3029 | 3029 _M_set(_Td{__v.data(), __v.size()}); /opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/string_view:146:7: 注意:候选者:'constexpr std::basic_string_view<_CharT, _Traits>::basic_string_view(const _CharT*, size_type) [with _CharT = 字符; _Traits = std::char_traits; size_type = 长无符号整数]' 146 | 146 basic_string_view(const _CharT* __str, size_type __len) noexcept | ^~~~~~~~~~~~~~~~~ /opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/string_view:146:39:注意:参数 1 没有从“wchar_t*”到“const char*”的已知转换 146 | 146 basic_string_view(const _CharT* __str, size_type __len) noexcept

将 libc++ 与 clang 结合使用,它可以工作 将 Clang 与 libc++ 结合使用

如有任何帮助,我们将不胜感激。

GCC/Clang libstd++ 失败

c++ c++20 libstdc++ wstring stdformat
1个回答
0
投票

这是一个 libstdc++ 的错误(PR 112607),已在 GCC-trunk 中修复

© www.soinside.com 2019 - 2024. All rights reserved.