-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy path002_grammar_user_defined_literals.cpp
69 lines (56 loc) · 1.29 KB
/
002_grammar_user_defined_literals.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <cstddef>
#include <algorithm>
#include <iostream>
#include <numbers>
#include <string>
// used as conversion from degrees (input param) to radians (returned output)
constexpr long double operator"" _deg_to_rad ( long double deg )
{
long double radians = deg * std::numbers::pi_v<long double> / 180;
return radians;
}
// used with custom type
struct mytype
{
unsigned long long m;
};
constexpr mytype operator"" _mytype ( unsigned long long n )
{
return mytype{n};
}
// used for side-effects
void operator"" _print ( const char* str )
{
std::cout << str << '\n';
}
#if __cpp_nontype_template_args < 201911
std::string operator"" _x2 ( const char* str, std::size_t )
{
return std::string{str} + str;
}
#else // C++20 string literal operator template
template<std::size_t N>
struct DoubleString
{
char p[N*2-1]{};
constexpr DoubleString ( char const(&pp)[N] )
{
std::ranges::copy(pp, p);
std::ranges::copy(pp, p + N - 1);
};
};
template<DoubleString A>
constexpr auto operator"" _x2()
{
return A.p;
}
#endif // C++20
int main()
{
double x_rad = 90.0_deg_to_rad;
std::cout << std::fixed << x_rad << '\n';
mytype y = 123_mytype;
std::cout << y.m << '\n';
0x123ABC_print;
std::cout << "abc"_x2 << '\n';
}