C++ 检查CRTP模式中派生类中的函数覆盖

C++ 检查CRTP模式中派生类中的函数覆盖,c++,c++11,crtp,C++,C++11,Crtp,我试图实现对CRTP模式正确实现的编译时检查 代码如下: #include <iostream> #include <type_traits> using namespace std; #define static_interface_check(BaseClass, DerivedClass, FuncName) \ static_assert(!std::is_same<decltype(&DerivedClass::FuncName), d

我试图实现对CRTP模式正确实现的编译时检查

代码如下:

#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;
}
#包括
#包括
使用名称空间std;
#定义静态接口检查(基类、派生类、FuncName)\
静态断言(!std::is_same::value,“CRTP错误:函数”#基类):“#FuncName”未在类“#DerivedClass”中覆盖;
模板
类接口
{
公众:
接口();
void foo1()
{
静态_cast(this)->foo1();
}
void foo2()
{
静态_cast(this)->foo2();
}
};
//检查内部接口声明会导致不完整的类型错误,因此我必须将其移动到默认构造函数
模板
接口::接口()
{
静态接口检查(接口,T,foo1);
静态接口检查(接口、T、foo2);
}
A类:公共接口
{
公众:

void foo1(){您是否可以从NVI模式中获得一些灵感,并使要重写的方法具有与
接口
的方法不同的名称(例如
doFoo1
doFoo2
)。这将起作用,但它有一个缺点:这些方法应该是非公共的,基类在开始时不键入
友元接口
就无法访问它们。