Z
Z
Zellily2017-09-29 15:13:49
C++ / C#
Zellily, 2017-09-29 15:13:49

How to change the value of an enum field at runtime?

Let's say I have some function that at some point in time will return either true or false. Depending on the result of this function, I need to set enum values:
Let's say there was an enum:
enum class Foo{qqq, www };
And it became like this:
Foo::qqq = 5; Foo::www = 10;
(this is pseudocode, it won't work like that, but you need something similar in meaning)
If this is not possible, then what options are generally possible in this case, if you need an enum with values ​​that change during operation? Maybe create two enums with the same name fields, and return a pointer to the enum depending on the true/false function?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
res2001, 2017-09-29
@res2001

enum are constants.
If you have only 2 options for values, then add additional values ​​to enum:
enum class Foo{qqq = 0, www = 1, qqq1 = 5, www1 = 10 };
If more - you need to change the scheme and use not enum.

G
GavriKos, 2017-09-29
@GavriKos

Purely on enams - no way. After compilation, there is no enam - there are just ints.
The simplest option in this case is map. The key is a string (or you can use the same enam if you prefer), the value is the current value of your own.

A
Anton Zhilin, 2017-09-30
@Anton3

You need tagged union. Here's what it would look like in Swift, for example:

enum Foo {
    case qqq(Int)
    case www(Int)
}

let x = Foo.qqq(5)
let y = Foo.www(10)

In C++, this is often emulated using inheritance:
class Foo {
public:
    virtual ~Foo() = 0;
};

class qqq : public Foo {
public:
    int value;
    explicit qqq(int value);
};

class www : public Foo {
public:
    int value;
    explicit www(int value);
};

using FooPtr = std::unique_ptr<Foo>;
FooPtr makeQqq(int value);
FooPtr makeWww(int value);

FooPtr x = makeQqq(5);
FooPtr y = makeWww(10);

I left out a small amount of code that I have no doubt you could finish yourself if you really want to make this monster work :)
There is a cleaner way: include a lib type_safe(clickable).
#include <type_safe/strong_typedef.hpp>
#include <type_safe/variant.hpp>

namespace ts = type_safe;

using qqq = ts::strong_typedef<int>;
using www = ts::strong_typedef<int>;
using Foo = ts::variant<qqq, www>;

// ...

auto x = Foo(qqq(5));
auto y = Foo(www(10));

if (x.has_value(ts::variant_type<qqq>{})) {
    qqq value = x.value(ts::variant_type<qqq>{}));
    std::cout << "qqq" << ' ' << static_cast<int>(value);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question