C++:用户定义的文本
简介
C + + 中有六种主要类别的文本:整数、字符、浮点、字符串、布尔值和指针。 从 c + + 11 开始,可以根据这些类别定义自己的文本,为常见惯例提供句法快捷方式并提高类型安全性。 例如,假设你有一个 Distance 类。 您可以为公里定义一个文本,为英里定义另一个文本,并通过编写:或来鼓励用户明确度量单位 auto d = 42.0_km auto d = 42.0_mi 。 用户定义的文本没有性能优势或缺点;它们主要是为了方便或编译时类型推导。 标准库为 std::string std::complex 标头中的 “时间” 和 “持续时间” 操作的用户定义的文本(对于和)具有用户定义的文本 :
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
用户定义的文本运算符签名
通过使用以下形式之一在命名空间范围内定义运算符 “” 来实现用户定义的文本:
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 opera