如何以多态方式初始化`static`成员 [英] How to initialize `static` member polymorphically

查看:58
本文介绍了如何以多态方式初始化`static`成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有基类 Validator.

class Validator
{
public:
  void validate(const string& str)
  {
    if( k_valid_keys.find(str) == k_valid_keys.end() ) 
      throw exception();
  }
private:
  const static std::set<string> k_valid_keys;
};

现在假设我需要扩展类Validator.每个派生类都有自己的一组有效键.
我的目标是:

Now assume I need to extend class Validator. Each derived class will have its own set of valid keys.
My goal is:

  1. k_valid_keys 成为 Validator 的成员.无需将其添加到每个派生类中,尤其是当派生类的类型不止几种时.
  2. 保持k_valid_keys 静态.假设我有多个 Validator 实例(及其派生类),并且 k_valid_keys 的初始化开销很大.
  1. keep k_valid_keys a member of Validator. No need to add it to each derived classes especially when there are more than a few types of those.
  2. keep k_valid_keys static. Assume I have multiple instances of Validator (and its derived classed) and initialization of k_valid_keys is expensive.

如何以多态方式初始化 static 成员?好吧,我知道这是不可能的(如果我错了,请纠正).

How can I initialize static member polymorphically? well, I know that it can't be done (please correct if I'm wrong).

所以假设它无法完成,有没有更好的设计来解决这个问题?

So Assuming it can't be done, any idea of a better design for this problem?

推荐答案

由于 k_valid_keysstatic 声明于 Validator,所有派生类from Validator 将共享 k_valid_keys 的相同实例.就是这样,您将不能在程序中同时拥有多个 Validator 子类的实例,否则 Validator 子类的不同实例将将元素添加到相同的结构中.

Since k_valid_keys is static declared at Validator, all the derived classes from Validator will share the same instance of k_valid_keys. That's it, you will not be able to have more than one instance of a subclass of Validator at the same time in your program, else your different instances of subclases of Validator will add elements to the same structure.

也就是说,类上的静态成员变量只是整个程序的全局变量.

That's is, a static member variable on a class is just a global variable of your entire program.

如果您有两个或多个 Validator 子类,但您保证只有一个实例,则只需在子类构造函数上初始化 k_valid_keys.

If you have two or more subclases of Validator but you guarantee that you are going to have only just one instance, you just initialize k_valid_keys on the subclass constructor.

这篇关于如何以多态方式初始化`static`成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆