I am learning designing principles course and as I was trying to implement a open close principle on my own where we define different specification which is then sent to filter class to check whether the given entity is valid entity or not.
These are my virtual class
template <typename T>
struct Specification {
virtual ~Specification() {}
virtual bool is_satisfied(T* item) = 0;
};
template <typename T>
struct Filter {
virtual std::vector<T*> filter(std::vector<T*> items, Specification<T>& spec) = 0;
};
template <typename T>
struct AndSpecification : Specification<T> {
Specification<T>& first;
Specification<T>& second;
AndSpecification(Specification<T>&& first, Specification<T>&& second) : first(first), second(second) {}
bool is_satisfied(T* item) override {
return first.is_satisfied(item) && second.is_satisfied(item);
}
};
struct BetterFilter : Filter<Product> {
std::vector<Product* > filter(std::vector<Product*> items, Specification<Product>& spec);
};
struct ColorSpecification : Specification<Product> {
Color color;
ColorSpecification(Color color) :color(color) {}
bool is_satisfied(Product* item);
};
struct SizeSpecification : Specification<Product> {
Size size;
SizeSpecification(Size size) :size(size) {}
bool is_satisfied(Product* item);
};
These are my inherited classes
And based on these classes I am trying to override && operator which is defined in global scope. `
template <typename T>
AndSpecification<T> operator&&(Specification<T>&& one, Specification<T>&& two) {
return AndSpecification<T>{one, two};
}
When I am trying to compile this I am getting error
Error C2440 '<function-style-cast>': cannot convert from 'initializer list' to 'AndSpecification<Product>' DesignPrinciples C:\Users\ania\source\repos\DesignPrinciples\Main.cpp 24
I tried different methods to define like
AndSpecification<Product> operator&&(Specification<Product>&& one, Specification<Product>&& two) {
return AndSpecification<Product>(one, two);
}
but even then it failed. Can someone explain me what am i doing wrong here. How can I rectify it ?
Edit1: Thanks to @Yksisarvinen I am able to compile when I add std::move in template method
AndSpecification<T> operator&&(Specification<T>&& one, Specification<T>&& two) {
return AndSpecification<T>{std::move(one), std::move(two)};
}
But when i run it, it fails with read access violation
I am getting this exception at this line
AndSpecification<Product> spec = ColorSpecification(Color::green) && SizeSpecification(Size::large);
Edit 2: Here is the minimal reproducible example.