2

lets say I have this simplified example:
I have some code that does serialization and deserialization of a class... first byte is enum that encodes class type(they all inherit from same base).. eg.

    Color* c;
    auto classType == read_byte(buffer);
    switch (classType)
    case eBlue:
    {
       c = new Blue(buffer);
    }
    case eGray:
    {
       c = new Gray(buffer)
    }

//...

is there any way to have a map from enum to type so I can replace switch

c = new enum2Type(buffer);

edit ofc I would never use raw ptr IRL.:)

3

2 Answers 2

3
template<typename T>
T* makeColor(Buffer const& buffer)
{
    return new T(buffer);
}

...

std::map<ColerEnum, Color* (*)(Buffer const&)> m;
m[grayEnum] = makeColor<Gray>;

...

Color* c = m[typeByte](buffer);
Sign up to request clarification or add additional context in comments.

Comments

1

You could replace your switch case by a map or array of functors with a buffer parameter, returning a (smart) pointer to Color:

enum EnumType { blueEnum, grayEnum };
struct Buffer { .... };
struct Color { .... };

template <typename T>
Color* make_stuff(const Buffer& b) { return new T(b); }

then

#include <functional>
#include <map>
...

// if you are sure enum values start at 0 and increase withoug jumps, 
// you could use a plain array
std::map<EnumType, std::function<Color*(const Buffer&)>> m;

m[grayEnum] = make_stuff<Gray>;
m[blueEnum] = make_stuff<Blue>;

Color* c = m.at(classType);

1 Comment

@NoSenseEtAl You can save some of the duplication by using a function template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.