如何传递一个临时数组? [英] How to pass a temporary array?

查看:27
本文介绍了如何传递一个临时数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何传递临时数组?我想做这样的事情:

How can I pass a temporary array? I want to do something like this:

#include <iostream>

int sum(int arr[]) {
    int answer = 0;
    for (const auto& i : arr) {
        answer += i;
    }
    return answer;
}

int main() {
    std::cout << sum( {4, 2} ) << std::endl;       // error
    std::cout << sum( int[]{4, 2} ) << std::endl;  // error
}

在函数参数的大括号 [] 中是否需要正整数文字?如果我包含那个文字,它会限制我只能传递给那个大小的数组的数组吗?另外,如何通过右值引用或常量引用传递数组元素?由于上述示例无法编译,因此我认为使函数的参数类型 int&&[]const int&[] 不起作用.

Do I need a positive integer literal in the function parameter's braces []? If I include that literal, will it limit what arrays I can pass to only arrays of that size? Also, how can I pass array elements by rvalue reference or const reference? Because the above sample doesn't compile, I presume making the function's parameter type int&&[] or const int&[] won't work.

推荐答案

首先,您不能将数组作为纯右值传递,因此您的函数需要引用.其次,数组的大小是类型的一部分,因此您的函数可能需要成为模板的一部分.第三,编写临时数组在词汇上有点傻,所以你需要一些噪音.

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}) << "\n";
}

int main()
{
    using X = int[3];
    std::cout << sum(X{1, 2, 3}) << "\n";
}

句法噪音可以用别名模板稍微概括:

The syntactic noise can be generalized slightly with an alias template:

template <std::size_t N> using X = int[N];

用法:sum(X<4>{1, 2, 3, 4})(您不能从初始化程序推导出模板参数.) 感谢 Jarod42 指出实际上完全有可能从花括号列表中推导出模板参数;不需要类型别名.

Usage: sum(X<4>{1, 2, 3, 4}) (You cannot have the template parameter deduced from the initializer.) 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.

这篇关于如何传递一个临时数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆