I have vector of objects and a vector of criteria to filter by. Inspired by Moo-Juice from this post, I wrote such a code:
#include <algorithm>
#include <string>
#include <memory>
#include <vector>
struct Token {
char code;
int val;
Token(char c,int a) : code(c),val(a) {}
};
class FilterBase {
public:
virtual bool operator()(const std::shared_ptr<Token> p) =0;
};
class ByCode : public FilterBase {
public:
ByCode( char c) : code_(c) {}
virtual bool operator()(const std::shared_ptr<Token> p) {
return code_ == p->code;
}
private:
unsigned char code_;
};
int main() {
std::vector<std::shared_ptr<FilterBase>> filters;
filters.push_back(std::make_shared<ByCode>('A'));
filters.push_back(std::make_shared<ByCode>('B'));
std::shared_ptr<Token> p = std::make_shared<Token>('M', 20);
std::vector<std::shared_ptr<Token>> tokens;
tokens.push_back(p);
filters[0]->operator ()(p);
for (const std::shared_ptr<FilterBase> fi : filters) {
tokens.erase(std::remove_if(tokens.begin(), tokens.end(), *fi), tokens.end());
}
}
But unfortunately it does not compile, because parameter type 'FilterBase' is an abstract class. Well I know it is, I just thoght the virtual keyword would make it working...