bblanchon / ArduinoJson

📟 JSON library for Arduino and embedded C++. Simple and efficient.
https://arduinojson.org
MIT License
6.7k stars 1.12k forks source link

Example code results in compiler error: no match for 'operator+=' #2087

Closed arjenhiemstra closed 4 months ago

arjenhiemstra commented 4 months ago

Describe the bug
Example code results in compiler error: no match for 'operator+='

Troubleshooter report
Here is the report generated by the ArduinoJson Troubleshooter:

  1. The program uses ArduinoJson 7
  2. The issue happens at compile time
  3. The error is not in the list

Environment
Here is the environment that I used:

Reproduction
Here is a small snippet that reproduces the issue.

JsonDocument doc;
deserializeJson(doc, "{\"first\":\"hello\",\"second\":\"world\"}");
JsonObject root = doc.as<JsonObject>();

int index = 1;

JsonObject::iterator it = doc.as<JsonObject>().begin();
it += index;

Serial.println(it->value().as<const char*>());

source: https://arduinojson.org/v7/api/jsonobject/begin_end/#get-object-member-by-index

Compiler output
If relevant, include the complete compiler output (i.e. not just the line that contains the error.)

test.cpp:7:14: error: no match for 'operator+=' (operand types are 'ArduinoJson::V704PB2::JsonObject::iterator' {aka 'ArduinoJson::V704PB2::JsonObjectIterator'} and 'int')
           it += index;
           ~~~^~~~~~~~

Program output
If relevant, include the repro program output. n/a

Expected output:

"world"

Actual output: none

bblanchon commented 4 months ago

Hi @arjenhiemstra,

Thank you very much for reporting this issue.

I don't think it was a good idea to add the += operator to a unidirectional iterator because it gives the wrong impression that you can go backward with += -1. I prefer not to add it back in v7, so instead of fixing the code, I updated the documentation.

Best regards, Benoit

arjenhiemstra commented 4 months ago

No prob! I understand that you want to drop it. Is it an idea/possible to support std::advance instead?

bblanchon commented 4 months ago

You should be able to define the += operator out of class. Something along those lines (not tested):

JsonObject::iterator& operator+=(JsonObject::iterator& iterator, size_t offset) {
  for (size_t i=0; i<offset; ++i)
    ++iterator;
  return iterator;
}

If you do want to support std::advance, you probably need to add more operators.