我有一個模板容器類,我從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