On 16.03.2016 01:27, JiiPee wrote:
> Is it possible to get a behaviour of "inherited" enum?
Not quite, because with a values type the Is-A relationship goes the
other way than with class inheritance, which is what you have in C++.
For example, a rational number is the result of dividing one integer by
another with ordinary division, like 3/4. The set of rationals includes
the set of integers, like the set of animals includes the set of dogs,
so an integer Is-A rational, like a dog Is-An animal. But it makes sense
in C++ to have an Animal base class and a Dog derived class, because the
Dog class /adds/ information and behavior, while it does not make sense
in C++ to have a Rational base class and an Integer derived class,
because the Rational class has more information (you need two integers
to describe a rational, in general): it's ungood base.
Generally the kind of relationship involved for Rational and Integer is
modeled (or implemented) by value conversion, while the kind of
relationship for Animal and Dog is modeled by reference conversion.
But a typed enumeration is not a class, so the value conversion
technique isn't applicable.
This leaves us with no proper tools to apply, and so it's all about
choosing some suitable compromise – slightly deficient one way or another...
> What I want is, that I have a class, something like:
>
> enum animal_type ....
>
> class Dog
> {
> public:
> animal_type GetType() { return animal_type::Dog; }
> };
>
> class Cat
> {
> public:
> animal_type GetType() { return animal_type::Dog; }
> };
>
> and later on if I create an elephant:
>
> class Elephant
> {
> public:
> animal_type GetType() { return animal_type::Elephant; }
> };
>
> So how to dynamically add elements to an enum or simulate it somehow so
> that when adding a new class I do not need to touch the original enum
> definition but I can add the type inside the new class.
Instead of these integer identifiers you can probably use typeid.
> I want to be able to call a function:
>
> void CheckAnimal(animal_type a)
> {
> if(a == animal_type::Elephant)
> ...
> }
>
> So all animals have the same type (like animal_type). I know I could
> create integer constants for each animal type in each class, but then
> they would be integer type which is "weak"... I would like to have
> something similar to enum or class-type.
The only practical way I can see is declare the enum type centrally,
with values for all possible types.
Cheers!,
- Alf