Last active
October 13, 2015 01:30
-
-
Save thiagomg/5e253b31be483d14bae0 to your computer and use it in GitHub Desktop.
Range loops - Writing safe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template<typename T> | |
void print1(T &msgs) { | |
for(const auto &msg : msgs) { | |
PublishMessage(msg); | |
} | |
} | |
template<typename T> | |
void print2(T &msgs) { | |
for_each(begin(msgs), end(msgs), [](const auto &msg) { | |
PublishMessage(msg); | |
}); | |
} | |
//-------------- | |
vector<Message> msgs {"MSG1","MSG2","MSG3","MSG4","MSG5"}; | |
vector<Message> empty_msgs {}; | |
auto msgs_sub1 = narrow_range(msgs, 1, -1); //[1:-1] | |
auto msgs_sub2 = narrow_range(msgs, 1, 2); //[1:2] | |
auto msgs_sub3 = narrow_range(msgs, 1, 5); //Empty | |
auto msgs_sub4 = narrow_range(msgs, 1, -5); //Empty | |
auto msgs_sub5 = narrow_range(empty_msgs, 1, -1); //Empty | |
print1(msgs_sub1); //shows items 1, 2, 3 | |
print2(msgs_sub1); //shows items 1, 2, 3 | |
print2(msgs_sub2); //shows items 1, 2 | |
print2(msgs_sub3); //empty | |
print2(msgs_sub4); //empty | |
print2(msgs_sub5); //empty |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment