我可以在没有实用程序的情况下分配和 return 吗?

Can I assign and return without a utility routine?

有没有一种方法可以在不创建实用程序的情况下“分配和 return”?这是我的代码:

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);
}

我可以在没有 assign() 实用程序的情况下实施 do_work() 吗?


do_work() 签名的原因是它非常方便:

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

如果你想 return 赋值操作的结果,你可以(在大多数情况下)不使用像 assign 这样的 'utility' 函数,因为赋值表达式 本身有值; from cppreference(加粗我的):

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.

或者,来自 this Draft C++17 Standard

8.5.18 Assignment and compound assignment operators       [expr.ass]

1   The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand; their result is an lvalue referring to the left operand. …

因此,正如评论中所建议的,您可以简单地使用以下内容:

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