C++ features by examples
17.cpp
Go to the documentation of this file.
1
15static_assert(__cplusplus == 201703);
16
17#include <bits/stdc++.h>
18
19using namespace std;
20
40constexpr pair deducted_pair(1, 2.3);
41static_assert(deducted_pair.second == 2.3);
42
44constexpr tuple deducted_tuple(4, 2, 2.5);
45static_assert(get<2>(deducted_tuple) == 2.5);
46
48template <typename T = float>
50 T val;
53};
54
57
58#if __cpp_deduction_guides > 201611
59
61template_struct template_default_arg_deduction;
62
63#endif
64
65vector<int> int_vector = {1, 2, 3, 4};
66
68
71
74
76array deduction_guide_array {1, 2, 3, 4};
77
83
84
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
105template<auto n> struct B { /* ... */ };
106
107B<5> b1; // OK: non-type template parameter type is int
108
110
111// Error:
112// B<2.5> b3;
113
114tuple<int, int> foo_tuple()
115{
116 // return make_tuple(1, -1);
117 return {1, -1};
118}
119
120template <auto... seq>
122};
123
126
147// explicit constexpr
148auto identity = [](int n) constexpr { return n; };
149static_assert(identity(1) == 1);
150
151// lambda with auto argument actually is a template
152
153// implicit auto constexpr:
154
155auto can_be_constexpr1 = [](auto a) { return a; };
156auto can_be_constexpr2 = [](int(*fp)(int), auto a) { return fp(a); };
157
158static_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
164auto 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
169constexpr int const_inc(int n)
170{
171 return [n] { return n + 1; }();
172}
173
174constexpr int(*inc)(int) = const_inc;
175static_assert(const_inc(1) == 2);