First off, you cannot pass arrays as prvalues, so your function needs to take a reference. Second, the size of the array is part of the type, so your function probably needs to be part of a template. Third, writing array temporaries is lexically a bit silly, so you need some noise.
Putting it all together, the following ought to work
template <std::size_t N>
int sum(const int (&a)[N])
{
int n = 0;
for (int i : a) n += i;
return n;
}
int main()
{
std::cout << sum({1, 2, 3}) << "
";
}
int main()
{
using X = int[3];
std::cout << sum(X{1, 2, 3}) << "
";
}
The syntactic noise can be generalized slightly with an alias template:
template <std::size_t N> using X = int[N];
Usage: sum(X<4>{1, 2, 3, 4})
(You cannot have the template parameter deduced from the initializer.) Edit: Thanks to Jarod42 for pointing out that it is in fact perfectly possible to deduce the template argument from a braced list; no type alias is needed.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…