File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -916,6 +916,7 @@ int main() {
916916
917917 Plain old data:
918918
919+ https://stackoverflow.com/questions/146452/what-are-pod-types-in-c
919920 http://stackoverflow.com/questions/4178175/what-are-aggregates-and-pods-and-how-why-are-they-special
920921 */
921922 {
Original file line number Diff line number Diff line change @@ -32,6 +32,35 @@ std::string map_to_str(std::map<K,V> map) {
3232 return result.str ();
3333}
3434
35+ // How to use the range pattern from a method.
36+ // The key is to static initialize the lambda map.
37+ class RangeSwitch {
38+ public:
39+ int method (int x) {
40+ static std::map<int ,std::function<void (int &)>> m = {
41+ {0 , [&](int &x){
42+ x = -1 ;
43+ }},
44+ {2 , [&](int &x){
45+ x = 0 ;
46+ }},
47+ {5 , [&](int &x){
48+ x = 2 ;
49+ }},
50+ {7 , [&](int &x){
51+ x = 5 ;
52+ }}
53+ };
54+ auto it = m.upper_bound (x);
55+ if (it == m.end ()) {
56+ x = 7 ;
57+ } else {
58+ it->second (x);
59+ }
60+ return x;
61+ }
62+ };
63+
3564int main () {
3665 /*
3766 Create initialized map.
@@ -260,20 +289,21 @@ int main() {
260289 { 6 , 5 },
261290 { 7 , 7 },
262291 };
263- std::map<int ,std::function<void ()>> m;
264292 int x;
265- m.emplace (0 , [&](){
266- x = -1 ;
267- });
268- m.emplace (2 , [&](){
269- x = 0 ;
270- });
271- m.emplace (5 , [&](){
272- x = 2 ;
273- });
274- m.emplace (7 , [&](){
275- x = 5 ;
276- });
293+ std::map<int ,std::function<void ()>> m = {
294+ {0 , [&](){
295+ x = -1 ;
296+ }},
297+ {2 , [&](){
298+ x = 0 ;
299+ }},
300+ {5 , [&](){
301+ x = 2 ;
302+ }},
303+ {7 , [&](){
304+ x = 5 ;
305+ }}
306+ };
277307 for (auto i = -1 ; i < 8 ; ++i) {
278308 auto it = m.upper_bound (i);
279309 if (it == m.end ()) {
@@ -283,5 +313,11 @@ int main() {
283313 }
284314 assert (x == result[i]);
285315 }
316+
317+ RangeSwitch rangeSwitch;
318+ for (auto i = -1 ; i < 8 ; ++i) {
319+ x = rangeSwitch.method (i);
320+ assert (x == result[i]);
321+ }
286322 }
287323}
Original file line number Diff line number Diff line change @@ -43,11 +43,13 @@ class Class {
4343
4444 // https://stackoverflow.com/questions/1197106/static-constructors-in-c-i-need-to-initialize-private-static-objects
4545 static OtherClass otherClassWithJ;
46+ private:
4647 static struct _StaticConstructor {
4748 _StaticConstructor () {
4849 otherClassWithJ.j = otherClassWithJ.i + 1 ;
4950 }
5051 } _staticConstructor;
52+ public:
5153
5254 // Static methods
5355
You can’t perform that action at this time.
0 commit comments