如何以多态方式初始化`static`成员 [英] How to initialize `static` member polymorphically
问题描述
假设我有基类 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:
- 让
k_valid_keys
成为Validator
的成员.无需将其添加到每个派生类中,尤其是当派生类的类型不止几种时. - 保持
k_valid_keys
静态
.假设我有多个Validator
实例(及其派生类),并且k_valid_keys
的初始化开销很大.
- keep
k_valid_keys
a member ofValidator
. No need to add it to each derived classes especially when there are more than a few types of those. - keep
k_valid_keys
static
. Assume I have multiple instances ofValidator
(and its derived classed) and initialization ofk_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_keys
是 static
声明于 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屋!