我在 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/