Range loops - Writing safe
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