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

Implement std::ops traits on references #335

Open
benfrankel opened this issue Sep 5, 2022 · 1 comment
Open

Implement std::ops traits on references #335

benfrankel opened this issue Sep 5, 2022 · 1 comment
Labels
enhancement New feature or request

Comments

@benfrankel
Copy link
Contributor

benfrankel commented Sep 5, 2022

It's good practice for both T and &T to implement e.g. Add<T> and Add<&T>, even if T: Copy. Primitive types already do this, but Vec2 etc. currently don't.

This is important in generic contexts such as struct Foo<T> { x: T }. T might not be Copy, so to avoid unnecessary cloning, you can impl<T> Add<&Foo<T>> for Foo<T> where T: Add<&T>. However, this excludes Foo<Vec2> because Vec2: !Add<&Vec2>.

The following paragraph from the std::ops documentation is relevant:

Many of the operators take their operands by value. In non-generic contexts involving built-in types, this is usually not a problem. However, using these operators in generic code, requires some attention if values have to be reused as opposed to letting the operators consume them. One option is to occasionally use clone. Another option is to rely on the types involved providing additional operator implementations for references. For example, for a user-defined type T which is supposed to support addition, it is probably a good idea to have both T and &T implement the traits Add and Add<&T> so that generic code can be written without unnecessary cloning.

@dphfox
Copy link

dphfox commented Apr 2, 2023

This would be very much appreciated. I'm often working with references to vectors throughout my codebase, and this is a common point of friction. I don't want to have to dereference my vectors just to include them in operations.

@bitshifter bitshifter added the enhancement New feature or request label Mar 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants