从外部类继承的C++嵌套类;不允许不完整的类型

标签 c++ enums algebraic-data-types

在 kotlin 中,有一种设计模式,您可以使用密封类模拟具有关联值的 swift 枚举,并使用嵌套类继承它

https://medium.com/@da_pacheco/using-kotlins-sealed-class-to-approximate-swift-s-enum-with-associated-data-7e0abac88bbf

例如; swift 有:

enum Barcode {
  case UPCA(Int, Int, Int, Int)
  case QRCode(String)
}

Kotlin 模仿:

sealed class Barcode {
  class UPCA(val system: Int, val manufacturer: Int, val product: Int, val check: Int) : Barcode()
  class QRCode(val productCode: String) : Barcode()
}

然后你可以做一些事情,比如有一个 Barcode 列表并遍历它们。

您也可以在 Java 和 C# 中使用此模式...没有“密封类”,因此您无法阻止 future 的人扩展该列表,但它已经足够接近并且非常方便。

所以现在我试图在 C++ 中执行此操作,但我收到错误消息“不允许使用不完整的类型”

class ActionToPerform
{
public:
  class ClearItems: public ActionToPerform
  { };
};

这在一定程度上是有道理的,因为在编译器遇到 ClearItems 时,ActionToPerform 类型没有完全声明,但它也很愚蠢和烦人。我可以将 ClearItems 类从 ActionToPerform 中移出,但这样我就失去了作用域/命名空间的好处。

有什么办法解决这个问题吗?或者这只是 C++ 的固有限制?

最佳答案

只需转发声明您的派生类:

class ActionToPerform
{
public:
  class ClearItems;
};

class ActionToPerform::ClearItems: public ActionToPerform
{ };

关于从外部类继承的C++嵌套类;不允许不完整的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59928089/

相关文章:

swift - 如何在具有关联值的枚举上使用 OR 运算符进行模式匹配?

c++ - 使用assert(f<char, int>()) 编译错误

c++ - 在 Tic-Tac-Toe 中检查是否获胜

c++ - Boost UTF unit_test_main 的命令行参数

typescript - 如何查看 Typescript 类型的完整扩展合约?

haskell - 声明我自己的类型并在 Haskell 的函数中使用它们

haskell - 为什么我不能在不同的数据类型之间重复使用相同的值构造函数?

c++ - GCC C++编译器中的零大小数组

ios - "Binary operator ' ~= ' cannot be applied to operands of type '

c - 从枚举中删除一个值而不更改其他值