Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C++ operator sugar - a C++ way of looping through array #14

Open
cztomczak opened this issue Jan 20, 2013 · 2 comments · Fixed by #21
Open

C++ operator sugar - a C++ way of looping through array #14

cztomczak opened this issue Jan 20, 2013 · 2 comments · Fixed by #21
Milestone

Comments

@cztomczak
Copy link

Hi,

The C++ wrapper is great, but I'm missing one thing: a way to loop through array in a c++ fool-proof way. I know that I can do this:

json_value arr = (*settings)["web_server"]["cgi_extensions"];
if (arr.type == json_array) {
    int length = arr.u.array.length;
    for (int i = 0; i < length; i++) {
    ...
    }
}

But, a newbie might forget the type checking and just go with:

json_value arr = (*settings)["web_server"]["cgi_extensions"];
int length = arr.u.array.length;
for (int i = 0; i < length; i++) {
...
}

If someone makes a mistake in the json file, so that array is missing or becomes a string, then this code will crash the application.

I love the C++ wrapper mostly that it is fool-proof, I can reference to a non-existing key and it just returns an empty string, I will mistake the types and it will just return 0, nothing bad happens. But when it comes to looping through arrays it's easy to make a mistake, I've done it already and I'm a little scared of writing such code.

What I'm looking for is some method like GetArrayLength() that will return array length or 0 when value is not an array.

Czarek.

@LB--
Copy link
Member

LB-- commented Mar 27, 2013

I added support for C++11 range-based for-loops in #21 but I wasn't able to make it do a type check because of the nested class structure preventing access to the type member variable. If I could somehow access type, I could return nullptr for both begin and end for the wrong type, thus not looping at all, but I don't know how to access type.

@jamesamcl
Copy link
Collaborator

@LB-- Hmm. You could access type by subtracting the offset of the nested struct from its address to obtain a json_value pointer?

@LB-- LB-- added this to the v1.2.0 milestone Aug 14, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants