简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM