c++ - 更改窄字符串编码或缺少 std::filesystem::path::imbue

标签 c++ utf-8 filepath c++17 boost-filesystem

我在 Windows 上,我正在从 std::string 构造 std::filesystem::path。根据构造函数引用(强调我的):

If the source character type is char, the encoding of the source is assumed to be the native narrow encoding (so no conversion takes place on POSIX systems)

如果我理解正确,这意味着字符串内容将被视为在 Windows 下以 ANSI 编码。要将其视为以 UTF-8 编码,我需要使用 std::filesystem::u8path() 函数。查看演示:http://rextester.com/PXRH65151

我希望 path 的构造函数将窄字符串的内容视为 UTF-8 编码。对于 boost::filesystem::path 我可以使用 imbue() 方法来做到这一点:

boost::filesystem::path::imbue(std::locale(std::locale(), new std::codecvt_utf8_utf16<wchar_t>()));

但是,我在std::filesystem::path 中没有看到这样的方法。有没有办法为 std::filesystem::path 实现这种行为?或者我需要到处吐 u8path 吗?

最佳答案

我对这个问题的解决方案是将 std::filesystem 完全别名为一个名为 std::u8filesystem 的不同命名空间,其中包含处理 std 的类和方法::string 为 UTF-8 编码。类以相同的名称继承它们在 std::filesystem 中的相应内容,而无需添加任何字段或虚拟方法以提供完整的 API/ABI 互操作性。概念代码的完整证明 here , 到目前为止只在 Windows 上测试过,并且到目前为止是完整的。以下代码段显示了助手的核心工作:

std::wstring U8ToW(const std::string &string);

namespace std
{
    namespace u8filesystem
    {

    #ifdef WIN32
        class path : public filesystem::path
        {
        public:
            path(const std::string &string)
                : fs::path(U8ToW(path))
            {
            }

            inline std::string string() const
            {
                return filesystem::path::u8string();
            }
        }
    #else
        using namespace filesystem;
    #endif
    }
}

关于c++ - 更改窄字符串编码或缺少 std::filesystem::path::imbue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42765168/

相关文章:

Python3 : File path problems

c++ - 为什么在 winapi 中转换 UTF16 -> UTF8 -> UTF16 后文件名有不同的字节?

linux - Haskell:quoteFile 在 unicode 字符上带有 "invalid byte sequence"的文本文件上失败

mysql - GoLang - 坚持使用 ISO-8859-1 字符集

c# - 不使用 System.IO.FileInfo 获取文件大小?

c++ - 为文件名添加唯一的后缀

python - 如果不是每次都重新编译,numpy ctypes "dynamic module does not define init function"错误

C++ Boost 图形库 : Building a vector of vertices visited in an undirected graph search?

c++ - 如何修复 C++ 中结构的段错误?

c++ - 尝试使用 ffmpeg C API 取消执行和删除文件