1

I want to write a c++ function and pass it a struct parameter like this:

struct vec2 { 
    float x,y;
};

void func(vec2 v);

int main() {
    func(vec2 { 10, 20 } ); // argument value from constructor
}

I want my function to take a reference instead but I get an error.

void func(vec2 &v); // reference instead of value
 
int main() {
    func(vec2 { 10, 20 } ); // error: No matching function for call to 'func'
}

Is it possible to pass this argument by reference instead of by value without moving the constructor outside of the function call?

aganm
  • 1,245
  • 1
  • 11
  • 30
  • 5
    You're running into the issue that [temporaries cannot bind to non-const lvalue references](https://stackoverflow.com/questions/1565600/how-come-a-non-const-reference-cannot-bind-to-a-temporary-object). If `func` doesn't modify `v`, make it take a `const vec2&`. If it does, are you sure it's appropriate to call it on a temporary? – Nathan Pierson Oct 24 '21 at 04:19

0 Answers0