0%

字面量运算符、静态断言

字面量运算符

字面量运算符只能以_开头,仅允许包括const char*, long double, unsigned long long int, char等在内的形参列表

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
#include <bits/stdc++.h>

class length
{
private:
double value;
public:
enum unit
{
meter,
kilometer,
millimeter,
centimeter,
inch,
foot,
yard,
mile
};
static constexpr double factors[] = {
1.0, 1000.0, 1e-3, 1e-2, 0.0254, 0.3048, 0.9144, 1609.344
};

explicit length(double v, unit u = meter)
{
value = v * factors[u];
}

friend length operator+(length lhs, length rhs)
{
return length(lhs.value + rhs.value);
}

double get() const noexcept { return value; }
};

length operator "" _m(long double v)
{
return length(v, length::meter);
}

length operator "" _cm(long double v)
{
return length(v, length::centimeter);
}

int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout << (1.0_m + 10.0_cm).get() << std::endl;
return 0;
}

静态断言

在编译期对表达式进行判断