In order to return different types from a function, the types must be related (see below). In addition, the return type must be a pointer or a smart pointer.
If you wish to communicate data of unrelated types back to the caller, you have two options:
- Take reference parameters to
struct
of each possible kind, or
- Take a callback that accepts elements of each possible kind.
First approach:
enum shape_t {Cube, Sphere};
shape_t parse(vector<uint8_t> data, cube &c, sphere& s) {
if (<data represents a cube>) {
c.width = ...
c.volume = ...
return Cube;
} else if (<data represents a sphere>) {
s.diameter = ...
s.mass = ...
return Sphere;
} else {
... // Handle error
}
}
Second approach:
struct parse_callback {
virtual void cube(const cube& c);
virtual void sphere(const sphere& s);
};
...
void parse(vector<uint8_t> data, parse_callback& cb) {
...
if (<data represents a cube>) {
cube c;
c.width = ...
c.volume = ...
cb.cube(c);
} else if (<data represents a sphere>) {
sphere s;
s.diameter = ...
s.mass = ...
cb.sphere(s);
}
}
If you do not mind making your classes inherit from a common base, you can return a smart pointer to a polymorphic type:
enum shape_kind {Cube, Sphere};
struct shape {
virtual ~shape() {}
virtual shape_kind kind() = 0;
};
struct cube : public shape {
shape_kind kind() { return Cube; }
};
struct sphere : public shape {
shape_kind kind() { return Sphere; }
};
shared_ptr<shape> parse(const vector<uint8_t> data) {
if (<data represents a cube>) {
return shared_ptr<shape>(new cube);
} else {
return shared_ptr<shape>(new sphere);
}
}
Demo.