Andreas Loanjoe
Andreas Loanjoe

Reputation: 2399

Enum co-variance/polymorphism?

Imagine I have an enum defining a common option like:

enum valueState
{
   uninitialized,
   min,
   max
}

Now imagine I have a more specific value state for specific value types, lets say:

enum floatValueState
{
   nan
}

Would there be any way to pass the valueState options as floatValueStates ? Or is there some other way to achieve this kind of abstraction of choices at compile time without too much template noise.

EDIT: Ofc they can implicitly convert to the type of enum, but how would you combine the two enums without overlapping values (like 0 = uninitialized, 4 = non) without specifying how many enums I will combine.

Upvotes: 0

Views: 82

Answers (2)

GhostCat
GhostCat

Reputation: 140457

Whilst it is technically possible to solve this (see the other answer) - there is some theoretical problem: this is probably a violation of the Liskov Substitution Principle. That principle guides us how to use inheritance in sound OO design.

And it states: each "usage" of the "base type" - you can insert the "derived type" there.

Given that context - how would you "embed" that "additional information nan" here?

In other words (pseudo code):

 valueState value = ...
 if (value == min || max) {
 ... } else {
   value must be uninitialized

But what if value would now be floatValueState?!

Upvotes: 0

kabanus
kabanus

Reputation: 25895

Because old style enums (non-class) are just integers (implicit conversion), you can pass them around with disregard to which you're actually using. This is dangerous, but allows you to do what you want easily. You would need to micro-manage the values though, to make sure nan and uninitialized are not the same thing:

enum floatValueState {
   nan = 3
}

Anything accepting a floatValueState will implicitly accept a ValueState, with no extra work - what you want, but again, dangerous. Specifically, anything accepting a ValueState will also accept a floatValueState - and that could break stuff.

Upvotes: 3

Related Questions