C ++ binds one variable to two others via links

In C ++, we can define a variable by reference:

int foo = 3; int &bar = foo; 

Then the following code

 cout << foo << " " << bar; 

will print

 3 3 

because the "value" of the string is bound to the foo value by reference (&). I am wondering if there is a way to bind the bar value to two variables? Let's say I have three variables: geddy, neil and alex, and I want neil to always be equal to alex + geddy. Is there a way to write something like:

 int alex = 4; int geddy = 5; int &neil = alex + geddy; 

So that neil returns 9? Then, if I changed alex to 7, will neil return 12?

+5
source share
1 answer

No, not at all. You could make a function or functor:

 int alex = 4; int geddy = 5; auto neil = [&]() { return alex + geddy; }; std::cout << neil() << "\n"; 
+6
source

All Articles