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

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

问题描述

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

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
}

我是否需要在函数参数的大括号[]中使用正整数文字?如果我包含该文字,是否会限制只能传递给该大小的数组的数组?另外,如何通过右值引用或const引用传递数组元素?因为上面的示例无法编译,所以我认为使函数的参数类型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.

推荐答案

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

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天全站免登陆