返回可变参数包的加法。

huangapple go评论60阅读模式
英文:

Return the addition of variadic parameter pack

问题

让我们假设我有一个名为sum的函数,它接受可变参数包。

这个函数需要使用运算符+将参数包中的所有参数相加。

注意: 它不能以任何方式使用运算符+=,只能使用运算符+(因为程序不能假设所有参数都有重载operator+=)。

然后,函数sum需要返回整个“总和”或累积相加的结果。

以下是它的基本结构:

template <class... Args>
auto sum(Args... args)
{
    // ... 代码部分
}

注意: 所有参数可能不是相同的类型,并且您可以假设参数包的所有类型都存在相应的operator+重载。

可能有用的信息是,我正在使用C++ 20。

英文:

Let's say I have a function sum that takes a variadic parameter pack.
<br>
This function needs to ADD UP all of the parameters of the parameter pack using the operator +.

NOTE: It CANNOT use the operator += in any way and can use only operator + (as the program CANNOT assume that all parameters have operator+= overloaded).

Then, function sum needs to return the whole "sum" or accumulative add-up.<br>

Here is the basic structure of what it would look like:

template &lt;class... Args&gt;
auto sum(Args... args)
{
    // ... The code
}

<br>

NOTE: All arguments may not be of the same type AND you can assume that a corresponding overload of the operator+ exists for all types of the parameter pack.

It may be helpful to know that I am using C++ 20.

答案1

得分: 9

使用C++17的折叠表达式,https://en.cppreference.com/w/cpp/language/fold。
在大多数情况下,您不需要指定返回类型。

#include <cassert>

template <class... Args>
auto sum(Args... args) {  // 或者 right_fold_plus
    return (args + ...);
}

int main() {
    auto s = sum(1, 2, 3);
    assert( s == 1 + 2 + 3 );
}

https://godbolt.org/z/1Yh118ETb

注意:需要使用一个函数来实现这一点,这在语言上几乎是偶然的,不幸的是,这也为函数赋予了“错误的名称”的机会(从某种意义上来说,它可以执行名称所不暗示的操作,比如字符串连接)。
从这个意义上说,sum 不是一个好的名称,因为它也可以被称为 concatenate
一个更中性的名称,没有语义暗示,可以称之为 right_fold_plus

... 或者干脆不给它起名字 [](auto... xs) {return (xs + ...);}(1, 2, 3)(参见https://godbolt.org/z/7x9PzrzY1)

英文:

Use C++17's fold expressions, https://en.cppreference.com/w/cpp/language/fold.
You don't need to specify the return type in most cases.

#include&lt;cassert&gt;

template &lt;class... Args&gt;
auto sum(Args... args) {  // or right_fold_plus
    return (args + ...);
}

int main() {
    auto s = sum(1, 2, 3);
    assert( s == 1 + 2 + 3 );
}

https://godbolt.org/z/1Yh118ETb

NOTE: It is pretty much an accident of the language that one needs a function to do this, which, unfortunately, opens the opportunity to give the "wrong name" to a function (in the sense that it can do something that the name doesn't imply, like concatenating strings).
In that sense, sum is not a good name because it could also be called concatenate.
A more neutral name, without semantic implications, would be to call it right_fold_plus.

... or simply not give it a name it at all [](auto... xs) {return (xs + ...);}(1, 2, 3) (see https://godbolt.org/z/7x9PzrzY1)

huangapple
  • 本文由 发表于 2023年7月17日 12:45:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76701549.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定