Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

c++ - Dynamic mapping of enum value (int) to type

It appeared that this problem is quite common in our job.

We we are sending an int or enum value through the network, then we receive it we would like to create/call a particular object/function.

The most simply solution would be to use the switch statement, like below:

switch (value) {
    case FANCY_TYPE_VALUE: return new FancyType();
}

It works fine, but we would have plenty of these switch blocks, and when we create new value and type, we would need to change all of them. It does seem right.

Other possibility would be to use the templates. But we cannot, since the value of enum is defined in runtime.

Is there any right design pattern for that, or any right approach?

It seems like a very general and common problem in every day coding...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try a map:

struct Base { };
struct Der1 : Base { static Base * create() { return new Der1; } };
struct Der2 : Base { static Base * create() { return new Der2; } };
struct Der3 : Base { static Base * create() { return new Der3; } };

std::map<int, Base * (*)()> creators;

creators[12] = &Der1::create;
creators[29] = &Der2::create;
creators[85] = &Der3::create;

Base * p = creators[get_id_from_network()]();

(This is of course really crude; at the very least you'd have error checking, and a per-class self-registration scheme so you can't forget to register a class.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...