Skip to content

Instantly share code, notes, and snippets.

@ueokande ueokande/cpp_closure.cpp
Last active Aug 29, 2015

Embed
What would you like to do?
C++ /= block
#include <functional>
#include <vector>
#include <iostream>
template <typename T>
class Array {
public:
Array(const std::initializer_list<T> &data)
: each(*this), keep_if(*this), data(data)
{}
struct each_t {
each_t(Array<T> &parent) : parent(parent) {}
void operator /= (std::function<void(T)> f) {
for (auto x : parent.data) { f(x); }
}
void operator /= (std::function<void(T, int)> f) {
for (auto it = parent.data.begin(); it != parent.data.end(); ++it) {
f(*it, it - parent.data.begin());
}
}
Array<T> &parent;
} each;
struct keep_if_t {
keep_if_t(Array<T> &parent) : parent(parent) {}
void operator /= (std::function<bool(T)> f) {
for (auto it = parent.data.begin(); it != parent.data.end(); ++it) {
if (!f(*it)) {
it = parent.data.erase(it) - 1;
}
}
}
Array<T> &parent;
} keep_if;
private:
std::vector<T> data;
};
int main() {
Array<char> array {'a', 'b', 'c', 'd', 'e'};
array.each /= [](char x){
std::cout << x << std::endl;
};
array.keep_if /= [](char x) {
return x <= 'c';
};
array.each /= [](char x, int i){
std::cout << i << ":" << x << std::endl;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.