how to overload the += operator with the operands of different types (if possible)
Instead of having an add() method in the repository, I would like to overload the += operator so that the expression
_repository += myModel;
will insert myModel开发者_StackOverflow中文版 into the database(after i submit changes)
I know that the objects of different type cannot be used in operator overloading. Still want to know if there is some alternate ways to accomplish this
Any help?
I would strongly, strongly urge you not to do this even if you can. It goes against how operator overloading is meant to be used - what would you return from your operator? A new "clone" of the repository, or just this
?
A generic method is the way to go here. Just say "no" to overusing operator overloading.
I know that the objects of different type cannot be used in operator overloading.
I'm not sure what you mean by that. You can, for example, make an operator +
inside the repository type which takes two parameters, one of the repository type and one of the model type.
As to overloading the +=
operator, there's no way to do that directly; rather, you get that as a side effect by overloading the +
operator (see Reference).
So the solution is to make operator +
of a repository and a model return the new repository (the original one with the model provided added), and that will make +=
have the desired effect as well.
NOTE: If what you do is return a new repository that is like the original one but with the new model added, then this seems a reasonable way to go about it. If, however, what you mean for this is to mutate the original repository, then this would lead to unidiomatic, misleading code, as you will need +
to change the repository just as if it was +=
!
精彩评论