我有一个模板容器类,我从MyContainer
派生。 MyContainer
定义了像Get()
,Set()
等方法来访问各个元素。我想做一个位字类实现为MyContainer<char>
,其中每个char
元素拥有CHAR_BIT
位数。但是,为了允许用户在单个位而不是整个字节上操作,我必须使Get()
和Set()
为虚拟,这是非法的。有什么替代品?虚拟模板变通办法
我正在考虑在派生类中定义GetBit()
和SetBit()
,但这会违反Liskov替换原则。 (认为一个SortMyContainer()
功能的。)
编辑:这里是一个简化的例子:
template <typename Datatype>
struct MyContainer
{
virtual Datatype Get();
};
template <typename Datatype> // Error: Templates may not be virtual.
virtual Datatype MyContainer<Datatype>::Get() // EDIT: The problem was on this line. The "virtual" keyword should only appear with the function declaration.
{
// ...
}
我可以向你传授NVI模式或模板方法吗?见http://www.gotw.ca/publications/mill18.htm。 STL通常是遵循这个原则来实施的。 – 2011-06-10 13:13:22