Skip to content

Commit f133b1f

Browse files
committed
Range switch method
1 parent 21adfc5 commit f133b1f

3 files changed

Lines changed: 52 additions & 13 deletions

File tree

‎cpp/class.cpp‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff 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
{

‎cpp/map.cpp‎

Lines changed: 49 additions & 13 deletions
Original file line numberDiff line numberDiff 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+
3564
int 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
}

‎cpp/static.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff 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

0 commit comments

Comments
 (0)