mardi 29 septembre 2015

Check function overwriting in the derived class in CRTP pattern

I'm trying to implement compile-time checking of correct implementation of CRTP pattern.

Here is the 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 " was not overwritten in the 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, so I had to move it to the 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 a;
    bar(a);

    return 0;
}

It fails during compilation as expected:

error: static assertion failed: CRTP error: function Interface::foo2 was not overwritten in the class T

But I want to use also function overloading, const and non-const versions of the same function.

The question is: how can I implement it for the interface containing void foo(), void foo(int) and void foo(int) const?

Aucun commentaire:

Enregistrer un commentaire