C++ function returning reference to array

后端 未结 5 1298
天命终不由人
天命终不由人 2021-01-04 08:47

Is there any other way to receive a reference to an array from function returning except using a pointer?

Here is my code.

int ia[] = {1, 2, 3};
decl         


        
5条回答
  •  Happy的楠姐
    2021-01-04 08:56

    Some alternatives I think are superior in C++14 onwards:

    auto and array reference trailing return type:

    template 
    auto array_ref_test(T(&array)[N]) -> T(&)[N]
    {
        return array;
    }
    

    decltype(auto):

    template 
    decltype(auto) array_ref_test(T(&array)[N])
    {
        return array;
    }
    

    Example usage:

    int array_ref_ [] = { 1, 2, 3, 4, 5 };   
    decltype(auto) array_ref_result = array_ref_test(array_ref_); //'decltype(auto)' preserves reference unlike 'auto'
    std::cout << std::size(array_ref_result);
    

提交回复
热议问题