0

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

  • If you want polymorphism, then you will need an instance and you will need `virtual`. If you don't, inheritance doesn't have much to offer here. The standard library actually does the complete opposite of what you are trying here, it's function objects don't inherit from anything but are instantiated. Anyway, C++20 introduces [Concepts](https://en.cppreference.com/w/cpp/language/constraints) which might be what you are looking for. – François Andrieux Mar 23 '20 at 18:56
  • 1
    Note that here are no `static` member functions in the code you've shown. Did you forget to include the `static` keyword? – François Andrieux Mar 23 '20 at 18:57
  • 1
    If you implement `BaseComparator` with the [CRTP](https://stackoverflow.com/questions/4173254/what-is-the-curiously-recurring-template-pattern-crtp) you could check if the derived type [has the required overload](https://stackoverflow.com/questions/87372/check-if-a-class-has-a-member-function-of-a-given-signature) with a `static_assert`. Edit : Depending on why you use inheritance already, it may be more or less practical. – François Andrieux Mar 23 '20 at 18:59
  • @FrançoisAndrieux, the goal here is not to use an inheritance but to make some kind of "interface" which all comparators should satisfy –  Mar 23 '20 at 19:29
  • Then Concepts is what you are looking for. It's implemented in C++20. – François Andrieux Mar 23 '20 at 20:22

1 Answers1

1

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.

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79
  • Thiis should work fine. But remember that if anyone forgets to inherit from the base type, their comparator will probably still work fine. Since no part of the base class is ever necessary, forgetting to inherit will probably not generate any kind of compile time diagnostic. It might be better to just perform the check for the presence of the member wherever the comparator is used instead. – François Andrieux Mar 23 '20 at 20:24