Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I assign and return without a utility routine?

Is there a way to "assign and return" without creating a utility routine? Here’s my code:

static int& do_work_(const int* p, int& result)
{
   result = (*p) * 10;
   return result;
}

template<typename T>
T& assign(const T* p, T& result)
{
   result = *p;
   return result;
}

int& do_work(const int* p, bool cond, int& result)
{
   return cond ? do_work_(p, result) : assign(p, result);
}

Can I implement func() without the assign() utility?


The reason for the do_work() signature is that it’s a nice convenience:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const int value=1;
int i, j;
if (do_work(&value, true, i) == do_work(&value, false, j)) {}

>Solution :

If you want to return the result of an assignment operation you can (in most cases) do so without a ‘utility’ function like your assign, because the assignment expression itself has a value; from cppreference (bolding mine):

The direct assignment operator expects a modifiable lvalue as its left
operand and an rvalue expression or a braced-init-list (since C++11)
as its right operand, and returns an lvalue identifying the left
operand after modification
.

Thus, as suggested in the comments, you can simply have the following:

int& do_work(const int* p, bool cond, int& result)
{
   return cond ? do_work_(p, result) : (result = *p);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading