禁用实例化基本结构的可能性

Disabling possibility of instantiation of base struct

我有两个不同结构(只是数据存储)的用例,它们共享一些共同的成员,例如

struct Foo {
  int i;
  int j;
};

struct Bar {
  int i;
  float f;
};

公共数据可以用基本结构表示,但我想禁用创建基本结构对象的可能性。

如果您使构造函数受保护,则只有派生 类 可以访问它:

struct Base {
  int i;
 protected:
  Base() = default;
};

可以人为地在基础class中引入一个抽象方法,例如

struct Base {
  int i;
 protected:
  virtual void blockMe() const = 0;
};

struct Foo : public Base {
  int j;
 private:
  void blockMe() const final {}
};

struct Bar : public Base {
  float f;
 private:
  void blockMe() const final {}
};