我试图使用Curiously Recurring Template Pattern实现静态多态性,当我注意到static_cast<>
通常在编译时检查一个类型是否实际上可以转换为另一个类型时,它错过了基类声明中的错字,从而允许代码向下转换基类类到它的兄弟姐妹之一:
#include <iostream>
using namespace std;
template< typename T >
struct CRTP
{
void do_it( )
{
static_cast< T& >( *this ).execute( );
}
};
struct A : CRTP< A >
{
void execute( )
{
cout << "A" << endl;
}
};
struct B : CRTP< B >
{
void execute( )
{
cout << "B" << endl;
}
};
struct C : CRTP< A > // it should be CRTP< C >, but typo mistake
{
void execute( )
{
cout << "C" << endl;
}
};
int main( )
{
A a;
a.do_it( );
B b;
b.do_it( );
C c;
c.do_it( );
return 0;
}
程序的输出是:
A
B
A
为什么演员表工作没有错误?如何进行编译时检查以帮助解决此类错误?