LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 174|回复: 0

用户定义的文本

[复制链接]
发表于 2024-1-23 23:36:57 | 显示全部楼层 |阅读模式
在 C++ 中,文本有六个主要类别:整数、字符、浮点、字符串、布尔和指针。 从 C++11 开始,可以基于这些类别定义你自己的文本,以便为常见惯用语提供快捷语法,并提高类型安全性。 例如,假设有一个 Distance 类。 你可以将一个文本定义为表示公里,将另一个文本定义为表示英里,并通过编写以下内容帮助用户明确度量单位:auto d = 42.0_km 或 auto d = 42.0_mi。 用户定义的文本没有任何性能优势或劣势;它们的主要作用在于方便或实现编译时类型推断。 标准库具有 std::string、std::complex 以及 <chrono> 标头中的时间和持续时间操作单位的用户定义文本:

C++
Distance d = 36.0_mi + 42.0_km;         // Custom UDL (see below)
std::string str = "hello"s + "World"s;  // Standard Library <string> UDL
complex<double> num =
   (2.0 + 3.01i) * (5.0 + 4.3i);        // Standard Library <complex> UDL
auto duration = 15ms + 42h;             // Standard Library <chrono> UDLs
用户定义的文本运算符签名
通过以下形式之一在命名空间范围定义 operator"" 来实现用户定义的文本:

C++

ReturnType operator "" _a(unsigned long long int);   // Literal operator for user-defined INTEGRAL literal
ReturnType operator "" _b(long double);              // Literal operator for user-defined FLOATING literal
ReturnType operator "" _c(char);                     // Literal operator for user-defined CHARACTER literal
ReturnType operator "" _d(wchar_t);                  // Literal operator for user-defined CHARACTER literal
ReturnType operator "" _e(char16_t);                 // Literal operator for user-defined CHARACTER literal
ReturnType operator "" _f(char32_t);                 // Literal operator for user-defined CHARACTER literal
ReturnType operator "" _g(const char*, size_t);      // Literal operator for user-defined STRING literal
ReturnType operator "" _h(const wchar_t*, size_t);   // Literal operator for user-defined STRING literal
ReturnType operator "" _i(const char16_t*, size_t);  // Literal operator for user-defined STRING literal
ReturnType operator "" _g(const char32_t*, size_t);  // Literal operator for user-defined STRING literal
ReturnType operator "" _r(const char*);              // Raw literal operator
template<char...> ReturnType operator "" _t();       // Literal operator template
上例中的运算符名是你提供的任意占位符,但需要前导下划线。 (仅标准库才允许定义不带下划线的文本。)在返回类型中,你可以自定义文本执行的转换或其他操作。 此外,这些运算符中的任何一个都可定义为 constexpr。

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表