0

I am using CTRP to define an interface in C++ as follows:

template <typename T>
class Interface {
public:
    inline void foo() { static_cast<T*>(this)->foo(); }
};

class Implementation : public Interface<Implementation> {
public:
    void foo();
};

Thus, if the Interface is used as such:

template <typename T>
void interfaceUser(Interface<T>& i) {
    i.foo();
}

This will end up calling the foo() method of the implementation.

However, the flaw in this method (which I would like to keep because the method names of the interface and implementation are the same), is that, if the implementation does not implement the method, the code still compiles but causes an infinite loop.

My question is, is there some way to use static_assert to compare the pointers of Interface::foo and static_cast<T*>(this)->foo to ensure that they are NOT the same and thus, that the function has been implemented?

Also, please let me know if I am going about this in completely the wrong way.

Thanks

Patrick Wright
  • 1,401
  • 7
  • 13
  • Why using same name? – Jarod42 Apr 01 '21 at 15:01
  • A deriving class has the oprion of inplementing its function as a static member. The hoops you'd need to jump in order to detect and support that are numerous (and if overloading is done, your checks will get uglier). A different name (a la non-virtual interface) is really the most painless choice. – StoryTeller - Unslander Monica Apr 01 '21 at 15:02

0 Answers0