Skip to content

Instantly share code, notes, and snippets.

@HalCanary
Created July 16, 2021 13:42
Show Gist options
  • Save HalCanary/4b0fbf84aaa642192ce16fb29148c061 to your computer and use it in GitHub Desktop.
Save HalCanary/4b0fbf84aaa642192ce16fb29148c061 to your computer and use it in GitHub Desktop.
C++ Protobuff proposal:

C++ Protobuff proposal:

Given the following proto file:

enum Key {
    Unknown = 0;
    KeyOne = 1;
    KeyTwo = 2;
}
message KeyValue {
    Key key = 1;
    int32 value = 2;
}
message Array {
    repeated KeyValue keyvalues = 1;
}

I end up writing a lot of functions that look like this:

void fill_array(Array* array, int32_t valueone, int32_t valuetwo) {
    array->clear_keyvalues();
    auto* kvs = array->mutable_keyvalues();
    KeyValue* kv = kvs->Add();
    kv->set_key(KeyOne);
    kv->set_value(valueone);
    kv = kvs->Add();
    kv->set_key(KeyTwo);
    kv->set_value(valuetwo);
}

But if the setter functions returned this, i.e. something like:

class KeyValue {
    /*...*/
    KeyValue* set_value(int64_t value) {
        /*...*/
        value_ = value;
        return this;
    }
    /*...*/
}

Then I could write fill_array much more cleanly:

void fill_array(Array* array, int32_t valueone, int32_t valuetwo) {
    array->clear_keyvalues();
    auto* kvs = array->mutable_keyvalues();
    kvs->Add()->set_key(KeyOne)->set_value(valueone);
    kvs->Add()->set_key(KeyTwo)->set_value(valuetwo);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment