【发布时间】:2011-09-12 11:23:45
【问题描述】:
我有一个名为MyContainer 的模板容器类。 MyContainer 定义了诸如Get()、Set() 等方法来访问单个元素。我想将一个位域类实现为MyContainer<char>,其中每个char 元素包含CHAR_BIT 位数。但是,为了允许用户对单个位而不是整个字节进行操作,我必须将 Get() 和 Set() 设为虚拟,这是非法的。有哪些替代方案?
我想在派生类中定义GetBit() 和SetBit(),但这会违反里氏替换原则。 (想想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 模式或模板方法吗?见gotw.ca/publications/mill18.htm。 STL 通常是在该原则之后实施的。
标签: c++ oop templates inheritance virtual