开发者

Determining whether a non-object variable is initialized in C++

开发者 https://www.devze.com 2023-01-18 16:59 出处:网络
So, let\'s say, in a class in C++, I have a variety of member variables. Structs, strings, ints, etc. etc. Could be anything. These variables can or cannot be set by the initialization of the object o

So, let's say, in a class in C++, I have a variety of member variables. Structs, strings, ints, etc. etc. Could be anything. These variables can or cannot be set by the initialization of the object of this class. Given int a, float b, char c, sometimes al开发者_JAVA百科l of them or none of them can be set. When they are set, they can be set to any possible value of the variable. I would like to find someway of setting, and determining whether or not a variable has been set without:

1) Lots of casting. I could always create a Data_Value decorator class that has a boolean, and template it to whatever the given variable is. This would require calling a_data_value.value and a_data_value.isInitialized.

2) Lots of extra Boolean variables. I'd rather not have bool a_initialized, bool b_initialized.

What I would really like to do is something like this:

Python add to a function dynamically

in C++, with any and all variables, including primitives. Tall order I know, and I'm fully expecting the pessimistic answer.


You're right. It's impossible to determine at runtime whether a primitive is "set". Some compilers will warn you for some cases of using uninitialized values, but this is not at all guaranteed.


I would use a nullable template. See http://www.codeproject.com/KB/mcpp/CNullable.aspx


Suppose you have

class Bob {
 int a;
 int b;
 double c;
 complex<double> d;
 Bob () : a(), b(), c(), d() {}
};

When you create a new Bob, everything will be set to default (zero in this case).

There is no set or not set state for primitive types. They always hold some value.


If you want to rewrite Python in C++ you can.

You'd need an efficient unordered_map class keyed by string. The string would be the variable name.

Each variable value would be a class (call it a VARIANT, heh) that can hold any primitive value.

Then instead of a C++ struct you'd make your "struct" be an instance of your unordered_map aka dictionary.

If the variable name is found in the dictionary then it was set and you can return the value. If it isn't found it was never set.

If you plan to reference your dictionary keys by name from within C++ you will want to use the following for efficiency:

Instead of:

VARIANT v = dict["name"];

Use:

static const std::string name_key("name");
VARIANT v = dict[name_key];

That way instead of building a std::string containing "name" for the key lookup every time into the function, it will be done once.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号