Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a cv-qualifier for a method that returns a reference to an array?

Tags:

c++

If I have a member function which returns a reference to an array (https://stackoverflow.com/a/5399014/4304120), how can I add a const qualifier to the function? This code doesn't compile under Visual C++ 2010.

struct A
{
    int data[10];

    // this compiles
    const int (&f1())[10]
    {
        return data;
    }

    // error C2143: syntax error : missing ';' before '<cv-qualifer>'
    const int (&f2())[10] const
    {
        return data;
    }
};
like image 843
Marian Spanik Avatar asked May 25 '16 13:05

Marian Spanik


People also ask

What is cv qualifier?

const volatile object - an object whose type is const-volatile-qualified, a non-mutable subobject of a const volatile object, a const subobject of a volatile object, or a non-mutable volatile subobject of a const object. Behaves as both a const object and as a volatile object.

What is a function qualifier C++?

In the C, C++, and D programming languages, a type qualifier is a keyword that is applied to a type, resulting in a qualified type. For example, const int is a qualified type representing a constant integer, while int is the corresponding unqualified type, simply an integer.


1 Answers

I'll propose few solutions which are in my opinion more readable than the extremely direct answer to this question. I'm sure there are C grammar enthusiasts out there and I apologize to them for I have terrible memory and I'm not able to remember those C rules.

Type alias

You can avoid the weird C-based grammar by using a type alias:

struct A {
    using data_type = int[10];
    data_type data;
    data_type& f1() { return data; }
    data_type const& f2() const { return data; }
};

Live demo

or with typedef (for before C++11):

struct A {
    typedef int data_type[10];
    data_type data;
    data_type& f1() { return data; }
    data_type const& f2() const { return data; }
};

Live demo

Auto

Since C++14 you can also use auto return types:

struct A {
    int data[10];
    auto& f1() { return data; }
    auto const& f2() const { return data; }
};

Live demo

Standard array

As of C++11 you can also just use std::array:

struct A {
    using data_type = std::array<int, 10>;
    data_type data;
    data_type& f1() { return data; }
    data_type const& f2() const { return data; }
};

Live demo

and simplify it to:

struct A {
    std::array<int, 10> data;
};

Live demo

which is somewhat functionally equivalent but easier on the eyes.

like image 73
Shoe Avatar answered Oct 04 '22 02:10

Shoe