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;
}
};
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.
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.
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.
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With