C++ features by examples
17.cpp
Go to the documentation of this file.
1
15
static_assert
(__cplusplus == 201703);
16
17
#include <bits/stdc++.h>
18
19
using namespace
std;
20
40
constexpr
pair
deducted_pair
(1, 2.3);
41
static_assert
(
deducted_pair
.second == 2.3);
42
44
constexpr
tuple
deducted_tuple
(4, 2, 2.5);
45
static_assert
(get<2>(
deducted_tuple
) == 2.5);
46
48
template
<
typename
T =
float
>
49
struct
template_struct
{
50
T
val
;
51
template_struct
() :
val
() {}
52
template_struct
(T
val
) :
val
(
val
) {}
53
};
54
56
template_struct
template_arg_deduction
{1};
57
58
#if __cpp_deduction_guides > 201611
59
61
template_struct
template_default_arg_deduction;
62
63
#endif
64
65
vector<int>
int_vector
= {1, 2, 3, 4};
66
68
70
deque
deduction_guide1_queue
(
int_vector
.begin(),
int_vector
.end());
71
73
deque
deduction_guide2_queue
{
int_vector
.cbegin(),
int_vector
.cend()};
74
76
array
deduction_guide_array
{1, 2, 3, 4};
77
80
vector
deduction_guide1_vector
(
int_vector
.begin(),
int_vector
.end());
82
vector
deduction_guide2_vector
{
int_vector
.begin(),
int_vector
.end()};
83
84
89
void
deduction_guides_17
()
90
{
91
assert(
deduction_guide1_queue
[0] == 1);
92
assert(*
deduction_guide2_queue
[0] == 1);
93
assert(
deduction_guide1_vector
[0] == 1);
94
assert(*
deduction_guide2_vector
[0] == 1);
95
}
96
105
template
<auto n>
struct
B
{
/* ... */
};
106
107
B<5>
b1
;
// OK: non-type template parameter type is int
108
109
B<'a'>
b2
;
110
111
// Error:
112
// B<2.5> b3;
113
114
tuple<int, int>
foo_tuple
()
115
{
116
// return make_tuple(1, -1);
117
return
{1, -1};
118
}
119
120
template
<
auto
...
seq
>
121
struct
my_integer_sequence
{
122
};
123
125
auto
seq
=
my_integer_sequence<0, 1, 2>
();
126
147
// explicit constexpr
148
auto
identity
= [](
int
n)
constexpr
{
return
n; };
149
static_assert
(
identity
(1) == 1);
150
151
// lambda with auto argument actually is a template
152
153
// implicit auto constexpr:
154
155
auto
can_be_constexpr1
= [](
auto
a) {
return
a; };
156
auto
can_be_constexpr2
= [](int(*fp)(int),
auto
a) {
return
fp(a); };
157
158
static_assert
(
can_be_constexpr2
(
can_be_constexpr1
, 3) == 3);
159
160
// error: non-constant condition for static assertion
161
// static int i=0;
162
// static_assert(can_be_constexpr2(can_be_constexpr1, i) == 0);
163
164
auto
non_const
= [](
auto
a) {
static
int
s;
return
a; };
165
166
// error: no specialization can be constexpr because of s
167
// static_assert(can_be_constexpr(non_const, 3)==3);
168
169
constexpr
int
const_inc
(
int
n)
170
{
171
return
[n] {
return
n + 1; }();
172
}
173
174
constexpr
int(*
inc
)(int) =
const_inc
;
175
static_assert
(
const_inc
(1) == 2);