2

I'm looking at the rapidjson code for possible integration. I can see that thanks to the new C++11 you can in fact do associative arrays in C++, although I'm not sure the speed advantages. However, in their example code I'm seeing this:

 Document document; // Default template parameter uses UTF8 and MemoryPoolAllocator.

    char buffer[sizeof(json)];
    memcpy(buffer, json, sizeof(json));
    if (document.ParseInsitu(buffer).HasParseError())
        return 1;

    printf("\nAccess values in document:\n");
    assert(document.IsObject());    // Document is a JSON value represents the root of DOM. Root can be either an object or array.

    assert(document.HasMember("hello"));
    assert(document["hello"].IsString());
    printf("hello = %s\n", document["hello"].GetString());

It looks like Document is a class that has methods being called, but at the same time he's able to access it using document["hello"] as an associative array? Is that what's going on here?

Mikey A. Leonetti
  • 2,834
  • 3
  • 22
  • 36
  • I don't see any contradiction here. It's just a syntactic thing. If in a language, collections are objects (as in C++), why shouldn't you be able to use both subscripting syntax and method calls to use them? – The Paramagnetic Croissant Sep 09 '15 at 16:36
  • C++ has associative arrays in the standard library (`std::map` and `std::unordered_map`), so this shouldn't be surprising... – rlbond Sep 09 '15 at 16:45
  • http://stackoverflow.com/questions/4294100/creating-a-class-indexer-operator-allowing-string-parameter-string-index – 001 Sep 09 '15 at 16:46

2 Answers2

3

In C++, operator[] can be overloaded by a class. Document must either have implemented an overload or derived from one that has.

The syntax is roughly:

class Foo {
public:
    AssociatedType operator [] (IndexingType i) {
        //...
    }
};

The AssociatedType may be a reference. The method may be const.

jxh
  • 69,070
  • 8
  • 110
  • 193
0

Operator overloading is available since early days of C++.

In RapidJSON, there are several overloaded operator[] defined in GenericValue, like:

template<typename Encoding, typename Allocator>
template<typename T >
GenericValue& rapidjson::GenericValue< Encoding, Allocator >::operator[](T* name)   

And GenericDocument is derived from GenericValue.

Milo Yip
  • 4,902
  • 2
  • 25
  • 27