c++ - Check function overwriting in the derived class in CRTP pattern -
i'm trying implement compile-time checking of correct implementation of crtp pattern.
here code:
#include <iostream> #include <type_traits> using namespace std; #define static_interface_check(baseclass, derivedclass, funcname) \ static_assert(!std::is_same<decltype(&derivedclass::funcname), decltype(&baseclass<derivedclass>::funcname)>::value, "crtp error: function " #baseclass "::" #funcname " not overwritten in class " #derivedclass); template <class t> class interface { public: interface(); void foo1() { static_cast<t*>(this)->foo1(); } void foo2() { static_cast<t*>(this)->foo2(); } }; // checking inside interface<t> declaration results in incomplete type error, had move default constructor template <class t> interface<t>::interface() { static_interface_check(interface, t, foo1); static_interface_check(interface, t, foo2); } class a: public interface<a> { public: void foo1() { cout << "a::foo1()" << endl; } }; template <class t> void bar(interface<t> &obj) { obj.foo1(); obj.foo2(); } int main() { a; bar(a); return 0; }
it fails during compilation expected:
error: static assertion failed: crtp error: function interface::foo2 not overwritten in class t
but want use function overloading, const , non-const versions of same function.
the question is: how can implement interface containing void foo()
, void foo(int)
, void foo(int) const
?
Comments
Post a Comment