I am not 100% sure I see the problem.
If the user1 derived type extends your base class (with more virtual methods) then that should be fine (of course your code will never know or understand these new methods but presumably you would not be calling them:
class B
{
virtual void doStuff() { /* Nothing */}
};
// User 1 version:
class U1: public B
{
virtual void doStuff()
{
this->doA();
this->doB();
}
virtual void doA() {}
virtual void doB() {}
};
// User 2 version can extend it differently.
Note:
If you are worried by slicing because you are storing objects in a vector that is a slightly different problem.
std::vector<B> objs;
objs.push_back(U1());
std::for_each(objs.begin(),objs.end(),std::mem_fun_ref(&B::doStuff));
这里的问题在于用户定义类型U1无法被复制到向量中,因为向量只保存B对象。这会削减U1中持有的额外数据。
解决此问题的方法是您需要在向量中持有指针。当然,这会带来其他异常安全性方面的问题。因此,boost拥有ptr_vector<>容器,以正确地持有对象,但仍能像对象一样使用它们。
#include <boost/ptr_container/ptr_vector.hpp>
......
boost::ptr_vector<B> objs;
objs.push_back(new U1());
std::for_each(objs.begin(),objs.end(),std::mem_fun_ref(&B::doStuff));