#include <iostream>
#include <vector>
#include <functional>
using namespace std;
class Container {
public:
void VisitElement(const std::function<bool(int)> &f) {
size_t cnt = eles.size();
for (size_t i = 0; i < cnt; ++i) {
int ele = eles[i];
if(f(ele)) {
return;
}
}
}
void AddEle(int ele) {
eles.push_back(ele);
}
private:
vector<int> eles;
};
int main() {
Container container;
for (int i = 0; i < 10; ++i) {
container.AddEle(i);
}
container.VisitElement([&](int ele) {
if (ele % 2 == 0) {
return false;
}
cout << ele << ", ";
return false;
});
}
#include <iostream>
#include <string>
#include <vector>
#include <functional>
using namespace std;
struct Demo {
unsigned long id;
string name;
};
class Factory {
public:
void ForEachProducts(const std::function<void(Demo)> &f) {
for (auto product : products) {
f(product);
}
}
void AddProduct(Demo &demo) {
products.push_back(demo);
}
private:
vector<Demo> products;
};
int main() {
Factory factory;
Demo demo;
demo.id = 1;
demo.name = "hello";
factory.AddProduct(demo);
demo.id = 2;
demo.name = "hello";
factory.AddProduct(demo);
demo.id = 1;
demo.name = "world";
factory.AddProduct(demo);
factory.ForEachProducts([&](Demo demo) {
if (demo.name == "hello") {
printf("matched\n");
}
return;
});
}
[1] https://www.zhihu.com/question/22955003
[2] https://www.cnblogs.com/wqpkita/p/7510852.html