I have the following use case, a struct with some boolean and int variables
struct a {
int field1;
bool field2;
bool field3;
};
I am refactoring this code, and writing a constructor for the struct , the problem is the default initialization of fields.
I am not criticizing any language construct here, but ideally I would want null to be part of the language itself
i mean I should be able to define for struct a as
a : field1(null.int), field2(null.bool), field3(null.bool) {}
C++ does not allow it since null.int or null.bool are not defined. Is the only way to do in C++ is
a: field1(-1), field2(false), field3(false) {}
You can do
struct a {
a():field1(), field2(), field3() { }
int field1;
bool field2;
bool field3;
};
And all fields will be zero and false respectively. If you want to say that the fields have an indeterminate value, i'm afraid you have to use other techniques. One is to use boost::optional:
struct a {
a():field1(int()), field2(bool()) { }
optional<int> field1;
optional<bool> field2;
optional<bool> field3;
};
Leaves field3 indeterminate. Access the values with *field_name. Test for a none value with field == boost::none or if(field) { ... }.
If you're looking for a type with values {true, false, null}, that type is not bool. However, boost::optional<bool> is such a type. In the same way, boost::optional<int> can hold any int, or no int at all.
[edit]
Or std::optional, since C++17.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With