Return array in C++

前端 未结 6 2055
情话喂你
情话喂你 2020-12-12 04:51

I am a total C++ noob, and I am having some trouble returning an array from my methods. I have a header file with the following method declaration:

virtual d         


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-12 05:26

    There is a technique for passing arrays that do not decay to pointers. You pass the array by reference, using the syntax below. The required "extra" parens are a syntactical wart, and probably why this usage is not more common. One gets used to it real fast, given the advantages.

    void sub(double (&foo)[4])
    {
        cout << sizeof(foo) << endl;
    }
    

    Prints 32, not sizeof(double*), because the type of foo really is a reference to an array of 4 doubles. Using templates, you can generalize to work for any size of array:

    template  sub(double (&foo)[N])
     {
        cout << sizeof(foo) << endl;
     }
    
     double bar[5];
     double zot[3];
     sub(bar); // ==> 40
     sub(zot); // ==> 24
    

    You can generalize again to handle an any-size array of anything:

    template void sub(T(&foo)[N])
        {
            cout << sizeof(foo) << endl;
        }
    
    double bar[5];
    char zot[3];
    sub(bar); // ==> 40
    sub(zot); // ==> 3
    

    and you now have something that captures the abstract idea of "sub" regardless of the type or size of the array you pass it.

提交回复
热议问题