namespace wtl
{
//
//the base class
//
template <typename subclass>
class base
{
public:
void show_message(){
subclass* sub = static_cast<subclass*>(this);
std::cout<<sub->get_message()<<std::endl;
}
std::string get_message(){
return "this is the base class";
}
};
//
//the sub_one class
//
class sub_one:public base<sub_one>
{
};
//
//the sub_two class
//
class sub_two:public base<sub_two>
{
public:
std::string get_message(){
return "this is the sub_two class";
}
};
};
输出结果如下:
D:\CPP>g++ main.cpp -o main.exe
D:\CPP>main.exe
this is the base class
this is the sub_two class
static_cast<>是关键,这个转换在静态编译时会匹配,则sub指针要么是sub_one,要么是sub_two。如果是sub_one,则由于sub_one没有覆盖get_message(),故寻找其父类base的get_message()并成功匹配。如果是sub_two,则由于sub_two覆盖了get_message()方法,直接匹配sub_two的get_message()方法。当然了,如果你写一个类 sub_three:public base{},则肯定失败,因为static_cast无法将sub_two转换成sub_three,他们没有继承关系。