C++中的自定义文字

U 爵士 D 定义 L 显微组织( UDL 在C++ 11中添加了C++。尽管C++提供了各种内置类型的文字,但这些都是有限的。

null

内置类型的文本示例:

// Examples of classical literals for built-in types.
42    // int
2.4    // double
3.2F    // float
'w'    // char
32ULL    // Unsigned long long
0xD0    // Hexadecimal unsigned
"cd"    // C-style string(const char[3]")

我们为什么使用UDL? 让我们考虑下面的例子来理解UDLS的需求。

long double Weight = 2.3; //  pounds? kilograms? grams?

// With UDL, we attach units to the values which has
// following advantages
// 1) The code becomes readable.
// 2) Conversion computations are done at compile time. 
weight = 2.3kg;
ratio = 2.3kg/1.2lb;

要计算上述比率,必须将它们转换为相同的单位。 UDL 帮助我们克服单位翻译成本。我们可以为用户定义的类型定义用户定义的文本,为内置类型定义新形式的文本。它们有助于提高代码中常量的可读性。价值 UDL 用编译器在编译时在代码中定义的实际值替换。 UDL的 虽然不会节省太多的编码时间,但越来越多的计算可以转移到编译时,以加快执行速度。

用户定义的文字示例:

"hello"s            // string
4.3i                // imaginary
101000111101001b    // binary
53h                // hours
234093270497230409328432840923849 // extended-precision

UDL 被视为对文本运算符的调用。只支持后缀形式。文本运算符的名称为 操作员“ 后跟后缀。

例1:

// C++ code to demonstrate working of user defined
// literals (UDLs)
#include<iostream>
#include<iomanip>
using namespace std;
// user defined literals
// KiloGram
long double operator "" _kg( long double x )
{
return x*1000;
}
// Gram
long double operator "" _g( long double x )
{
return x;
}
// MiliGram
long double operator "" _mg( long double x )
{
return x / 1000;
}
// Driver code
int main()
{
long double weight = 3.6_kg;
cout << weight << endl;
cout << setprecision(8) << ( weight + 2.3_mg ) << endl;
cout << ( 32.3_kg / 2.0_g ) << endl;
cout << ( 32.3_mg *2.0_g ) << endl;
return 0;
}


输出:

3600
3600.0023
16150
0.0646

例2:

#include <iostream>
#include <complex>
using namespace std;
// imaginary literal
constexpr complex < double > operator "" _i( long double d )
{
return complex < double > { 0.0 , static_cast < double > ( d ) };
}
int main()
{
complex < double > z = 3.0 + 4.0_i;
complex < double > y = 2.3 + 5.0_i;
cout << "z + y = " << z+y << endl;
cout << "z * y = " << z*y << endl;
cout << "abs(z) = " << abs (z) << endl;
return 0;
}


输出:

z + y = (5.3,9)
z * y = (-13.1,24.2)
abs(z) = 5

在这里 常量表达式 用于启用编译时计算。

限制: UDL只能使用以下参数:

char const*
unsigned long long
long double
char const*, std::size_t
wchar_t const*, std::size_t
char16_t const*, std::size_t
char32_t const*, std::size_t

但返回值可以是任何类型。

本文由 马希玛·瓦尔什尼 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享