我正在尝试实现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;
}
在编译过程中按预期失败:
错误:静态断言失败:CRTP错误:函数Interface :: foo2 在T级没有被覆盖
但我想使用同一函数的函数重载,const和非const版本。
问题是:我如何为包含void foo()
,void foo(int)
和void foo(int) const
的界面实现它?