我在閱讀thrift源代碼的時候,看到了類似於下面的繼承設計,為什麼不直接重載read, write, 而是要寫個read_virt, write_virt這些函數呢?
#include <boost/shared_ptr.hpp>
#include <iostream>
class Parent {
public:
void read() {
read_virt();
}
virtual void read_virt() {
}
void write() {
write_virt();
}
virtual void write_virt() {
}
};
class DefaultSon : public Parent {
public:
virtual void read_virt() {
std::cout << "DefaultSon read" << std::endl;
}
virtual void write_virt() {
std::cout << "DefaultSon write" << std::endl;
}
};
template <class Me, class super_ = DefaultSon>
class VirtualParent: public super_ {
public:
virtual void read_virt() {
return static_cast<Me *>(this)->read();
}
virtual void write_virt() {
return static_cast<Me *>(this)->write();
}
};
class GoodSon : public VirtualParent<GoodSon> {
public:
void read() {
std::cout << "GoodSon read" << std::endl;
}
void write() {
std::cout << "GoodSon write" << std::endl;
}
};
class BadSon : public VirtualParent<BadSon> {
public:
void read() {
std::cout << "BadSon read" << std::endl;
}
void write() {
std::cout << "BadSon read" << std::endl;
}
};
int main() {
boost::shared_ptr<Parent> p(new GoodSon());
p->read();
p->write();
boost::shared_ptr<Parent> q(new BadSon());
q->read();
q->write();
}
這個是一個典型的OO設計中的技巧。我們一般管這種設計叫做NVI(Non-Virtual Interface)模式。
http://blog.csdn.net/acloudhuang/article/details/4465084