Does std :: get on std :: array use better performance?
The standard library class template std::array<T, N>
has a membership access function
constexpr const T& operator[]( size_type n ) const;
and also a non-member accessor function template
template< size_t I, class T, size_t N >
constexpr const T& get( const array<T,N>& a ) noexcept
In C ++ 17 all the overloads operator[]
were done constexpr
, so I wonder what, if any, are the rest of the benefits std::get
. For example. in a program like this:
int main()
{
auto a = std::array<int, 3> { 1, 2, 3 };
constexpr auto idx = 0;
std::cout << a[idx] << '\n';
std::cout << std::get<idx>(a) << '\n';
}
any decent compiler should be able to propagate the constant index value 0
for operator[]
and get
.
The question is : what benefits does it make std::get
on std::array
what operator[]
not?
source to share
The question is: what benefits does it make
std::get
onstd::array
whatoperator[]
not?
In addition to providing a common interface with the tuple, which we appear to be implicitly defining product types in C ++, std::get
has another advantage. Compile-time bounds checking:
std::array<int, 3> arr;
arr[4] = 17; // bad
std::get<5>(arr) = 42; // bad, but also compile error, so actually good
This is because the interface of a tuple is clearly ill-formed if the index is out of bounds (see [array.tuple] ), but operator[]
this is just a runtime problem that you should keep track of.
source to share