Reputation:
I am trying to create Comparator class for objects of some class A. To achieve this I want to create base class BaseComparator
and derive AComparator
and BComparator
from it. Is there a way to force all classes derived from BaseComparator
to implement function bool compare(const A &a, const A &b)
so
class AComparator : public BaseComparator {
static bool compare(const A &a, const A &b) { return true; }
}
will compile and
class BComparator : public BaseComparator {
}
will throw a compile-time error?
There is a way to achieve this with abstract class, which doesn't satisfy me as it requires a class to have a pure virtual function (while my classes don't have a state but only static functions and I do not need their instances).
Upvotes: 0
Views: 658
Reputation: 13634
You can use CRTP, and check passed derived class that:
It is really derived class. You can static_assert
on std::is_base_of
It has this member function as static function. You can try to access qualified name and static_cast it to function pointer type.
Upvotes: 1