Search code examples
c++c++11c++14return-type

Returning reference to an array of specific size without explicitly stating the size in return type


I've got the following function:

... getX()
{
    static int x[] = {1, 2, 3};
    return x;
}

I'd like to have its return type as int(&)[3] but don't wan't to specify the size (3) explicitly.

How do I do that?

(Please don't ask why I want that.)

UPD

Well, OK, I need to pass a result to a template function taking int(&x)[N] as a parameter (and I don't want to pass the size explicitly to that template function), so I don't see how a solution with returning a pair could work...


Solution

  • In C++14:

    auto& getX()
    {
        static int x[] = {1, 2, 3};
        return x;
    }
    

    Also, consider using std::array instead of C-style arrays.


    I cannot currently think of any Standard-compliant C++11 solution. Here's one using compound literals, assuming that your goal is to not repeat the elements and to deduce a reference-to-array:

    #include <type_traits>
    
    #define ITEMS 1, 2, 3
    auto getX() -> decltype((int[]){ITEMS})
    {
        static int x[] = {ITEMS};
        return x;
    }
    #undef ITEMS
    
    int main()
    {
        static_assert(std::is_same<decltype(getX()), int(&)[3]>{});
    }