Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

c++ - How to pass a temporary array?

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
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...