Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using std::get on std::array give better performance?

The Standard Library class template std::array<T, N> has both a member accessor function

constexpr const T& operator[]( size_type n ) const;

as well as 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 operator[] overloads have been made constexpr, so I wonder what, if any, are the remaining advantages of std::get. E.g. 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 both operator[] and get.

Question: what benefits does std::get on std::array give that operator[] doesn't?

like image 795
TemplateRex Avatar asked Dec 07 '25 08:12

TemplateRex


1 Answers

Get is required for structured bindings.

Other generic tuple code will also use it.

like image 189
Yakk - Adam Nevraumont Avatar answered Dec 08 '25 22:12

Yakk - Adam Nevraumont



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!