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++: setter functions should return self reference #562

Closed
feiyunw opened this issue Jul 1, 2015 · 3 comments
Closed

C++: setter functions should return self reference #562

feiyunw opened this issue Jul 1, 2015 · 3 comments

Comments

@feiyunw
Copy link

feiyunw commented Jul 1, 2015

For example:
message Person {
string name = 1;
int32 id = 2;
...
}
C++ setter functions should have the self-class referece as their return values:
inline Person& Person::set_name(...) { ...; return *this; };
inline Person& Person::set_id(...) { ...; return *this; };

Thus, we can set all fields in one line:
Person person;
person.set_name("Alice").set_id(1);

It will be more useful with more fields.

@arhadthedev
Copy link

What is a real reason for this proposal? As I know, the only kind of functions in C++ that should return a reference to invoked instance are assignment operators, e. g. copy-assignment and move-assignment ones. So any other function must return either a result or nothing.

I agree that some languages greet invocation chains, but C++ is not such case.

@ChrisJefferson
Copy link

@arhad : There is nothing wrong with invocation chains, and certainly no rule that they are "forbidden" in C++. They are indeed less common than in other languages, but you can find them in popular C++ libraries such as 'boost'.

I'm not saying if they should be added here, but I don't think it is a terrible idea.

@xfxyjwf
Copy link
Contributor

xfxyjwf commented Jan 21, 2016

For C++ setters, the more conventional way is for them to return void. It's not worthwhile to change the API to support chaining.

@xfxyjwf xfxyjwf closed this as completed Jan 21, 2016
taoso pushed a commit to taoso/protobuf that referenced this issue Aug 1, 2018
…rotocolbuffers#562)

The generator includes a hack for generating the name of fields which
extend proto2.bridge.MessageSet. (The ultimate motivation appears to
be compatibility with proto1 text formats.) Apply this hack based
on whether the message being extended defines the message_set_wire_format
option, not on the local name of that message type.
adellahlou pushed a commit to adellahlou/protobuf that referenced this issue Apr 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants