Namespaces
Variants

std::filesystem::path::generic_string, std::filesystem::path::generic_wstring, std::filesystem::path::generic_u8string, std::filesystem::path::generic_u16string, std::filesystem::path::generic_u32string

来自 zh.cppreference.net
 
 
 
 
template< class CharT, class Traits = std::char_traits<CharT>,
          class Alloc = std::allocator<CharT> >
std::basic_string<CharT,Traits,Alloc>
    generic_string( const Alloc& a = Alloc() ) const;
(1) (自 C++17 起)
std::string generic_string() const;
(2) (自 C++17 起)
std::wstring generic_wstring() const;
(3) (自 C++17 起)
std::u16string generic_u16string() const;
(4) (自 C++17 起)
std::u32string generic_u32string() const;
(5) (自 C++17 起)
std::string generic_u8string() const;
(6) (自 C++17 起)
(C++20 前)
std::u8string generic_u8string() const;
(自 C++20 起)

以通用路径名格式返回内部路径名,并转换为特定的字符串类型。如有转换,则按如下规定进行:

  • 如果 path::value_type 为 char,则转换(如果有)是与系统相关的。这通常出现在典型的 POSIX 系统(如 Linux)上,其中本地编码为 UTF-8,而 string() 不执行任何转换。
  • 否则,如果 path::value_type 为 wchar_t,则转换(如果有)是未指定的。这通常出现在 Windows 上,其中 wchar_t 为 16 位且本地编码为 UTF-16。
  • 否则,如果 path::value_type 为 char16_t,则本地编码为 UTF-16 且转换方法未指定。
  • 否则,如果 path::value_type 为 char32_t,则本地编码为 UTF-32 且转换方法未指定。
  • 否则,如果 path::value_type 为 char8_t,则本地编码为 UTF-8 且转换方法未指定。

使用 / 字符作为目录分隔符。

1) 所有内存分配均由 a 执行。
6) 在 u8string() 的情况下,结果编码始终为 UTF-8。

参数

a - 用于构造字符串的分配器
类型要求
-
CharT 必须是以下编码字符类型之一 ( char , wchar_t , char8_t (自 C++20 起) , char16_t 和 char32_t )。

返回值

通用路径名格式中的内部路径名,已转换为指定的字符串类型。

异常

可能抛出实现定义的异常。

示例

#include <cstddef>
#include <filesystem>
#include <iomanip>
#include <iostream>
#include <span>
#include <string_view>
void print(std::string_view rem, auto const& str)
{
    std::cout << rem << std::hex << std::uppercase << std::setfill('0');
    for (const auto b : std::as_bytes(std::span{str}))
        std::cout << std::setw(2) << std::to_integer<unsigned>(b) << ' ';
    std::cout << '\n';
}
int main()
{
    std::filesystem::path p{"/家/屋"};
    std::cout << p << '\n';
    print("string    : ", p.generic_string());
    print("u8string  : ", p.generic_u8string());
    print("u16string : ", p.generic_u16string());
    print("u32string : ", p.generic_u32string());
    print("wstring   : ", p.generic_wstring());
}

可能的输出:

"/家/屋"
string    : 2F E5 AE B6 2F E5 B1 8B
u8string  : 2F E5 AE B6 2F E5 B1 8B
u16string : 2F 00 B6 5B 2F 00 4B 5C
u32string : 2F 00 00 00 B6 5B 00 00 2F 00 00 00 4B 5C 00 00
wstring   : 2F 00 00 00 B6 5B 00 00 2F 00 00 00 4B 5C 00 00

参见

返回转换为字符串的本机路径名格式路径
(公开成员函数)