Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I conditionally choose which variable to assign to?

Essentially the same as this question, but for C++.

The simplest way to do this would be:

if (condition) {
    a = f(x);
} else {
    b = f(x);
}

While this meets my needs, it has always been bugging me that I've had to repeat typing f(x) twice, not to mention expanding the code out over so many lines when only one line will be executed. What if I have a larger set of destination variables to choose from?

switch(condition variable) {
case 1:
    var1 = f(x);
    break;
case 2:
    var2 = f(x);
    break;
...
case y:
    vary = f(x);
    break;
}

This looks very inelegant to me.

Is there anything in C++ that essentially allows me to do the following?

do-something-that-returns-a-lvalue = f(x);

Pardon me if it's not called a lvalue, I'm still relatively new to C++. But you guys know what I mean - the destination variable to assign a value to.

like image 252
thegreatjedi Avatar asked Dec 11 '15 01:12

thegreatjedi


2 Answers

You can form a reference or a pointer to the variable you want to assign.

(condition ? a : b) = f(x);  // reference

The above version was suggested by aschepler in a comment.

*(condition ? &a : &b) = f(x);  // pointer

The reference version is basically equivalent to the following more verbose example using a helper function.

template <typename T>
T&
conditional_reference(bool pred, T& yes, T& no) noexcept
{
  return pred ? yes : no;
}

// And then later

conditional_reference(condition, a, b) = f(x);

My point is that your traditional if then else control flow is probably still the best choice in terms of code clarity.

If the source of the assignment is a more complex expression than just f(x), you may store its result in a temporary variable and then only assign that variable in your conditional. C++11 move semantics make the use of such temporaries acceptable in many cases.

like image 152
5gon12eder Avatar answered Sep 18 '22 02:09

5gon12eder


If you can decide which variable to assign to at compile time, then you can get away with this very clean and zero-overhead approach:

std::get<constexpr_indexer()>(std::tie(var1, var2, var3, var4)) = f(x);

std::get, std::tie

like image 34
Brian Rodriguez Avatar answered Sep 18 '22 02:09

Brian Rodriguez