user10441785
user10441785

Reputation:

C++ force derived classes to implement static function

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

Answers (1)

Alex Guteniev
Alex Guteniev

Reputation: 13634

You can use CRTP, and check passed derived class that:

  1. It is really derived class. You can static_assert on std::is_base_of

  2. 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

Related Questions