在派生类中强制实施受保护的构造函数

6

有没有机制可以强制在派生类中实现受保护的构造函数?

简单示例:

template<typename T>
class Factory;

class Base {
  template<typename T>
  friend class Factory;
protected:
  Base();
};


class Child : public Base {
public:
  Child(); // this should lead to a compile time error
};

<template T>
class Factory {
Base* GetNew()
{
  BOOST_STATIC_ASSERT(boost::is_base_of<Base, T>::value);

  Base* b = new T();
  b->doStuff();

  return b;
 }
};

我希望Child类只能由工厂创建,并强制所有继承自Base的子类具有受保护的构造函数。

2个回答

4

简短回答,不是很。

protected是最不实用的访问修饰符,因为派生类可以自由地将名称(包括构造函数名称)设为public。

您可以在构造函数中使用访问键来确保只有工厂才能创建该类。

struct factory;

// create_key's constructor is private, but the factory is a friend.
class create_key
{
  create_key() {};
  friend factory;
};

struct only_from_factory
{
  // base constructor demands a key is sent. Only a factory may create a key.
  only_from_factory(const create_key&) {};
};

谢谢,这个主意非常好。实际上我也在考虑类似的东西。我也想接受你的答案,但很遗憾我只能接受一个。 - Chris
1
没关系,我做这个并不是为了荣耀。我这么做是因为(a)它让我保持警觉,(b)我碰巧认为C++是一门很棒的语言,我喜欢看到它被很好地使用。 - Richard Hodges

4

不,无法强制执行此操作。通常情况下,基类在约束子类方面非常有限。Base 不应该尝试负责监管每个可能继承 Base 的人编写的类。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接