【发布时间】:2017-05-08 16:54:13
【问题描述】:
我正在学习 C++,但我无法从 C# 中引入这种设计模式。如果这种模式在 C++ 中不起作用,或者我的语法不正确,我无法确定。
在示例中,我想创建一个解码 bitset 的类。
在带有泛型的 C# 中,它看起来像这样:
abstract class Base<T>
{
public abstract T GetValue(BitArray bits);
}
class Derived : Base<MyType>
{
public override MyType GetValue(BitArray bits)
{
// Do some magic to decode this bitset
}
}
这是我在 C++ 中的幼稚尝试
template<T,Q>
class Base
{
public:
Base() = default;
virtual ~Base() = 0;
virtual T* GetValue(const std::bitset<Q>& bits) const = 0;
}
class Derived : Base<MyType, 32>
{
public:
Derived();
~Derived();
MyType* GetValue(const std::bitset<32>& bits) const;
}
MyType* Derived::GetValue(const std::bitset<32>)
{
// Do some magic to decode this bitset
}
当我尝试编译该 C++ 代码时,编译器会抛出各种错误(我认为这在很多方面都是错误的)。
如何实现让继承类在 C++ 中为基类模板指定类型参数的模式?
【问题讨论】:
-
您在类声明后忘记了分号。
-
MyType是一个类,还是应该是Derived的模板参数? -
a class that decodes a bitset- 这是什么意思?您应该向我们展示您的MyType。此外,对于这种特殊情况,没有必要拥有虚拟基类,因为看起来这个方法应该是静态的 -
您也很可能希望使用公共继承,而不是私有(默认情况下)。尝试将
class Derived : Base更改为class Derived : public Base
标签: c# c++ templates generics polymorphism