admin管理员组

文章数量:1357273

When writing:

std::vector<double> vec{1.0,2.0};
std::span<const double> s(vec);
s[0]=1.0;

I get a compiler error, as expected:

Cannot assign to return value because function 'operator[]' returns a const value

However, when I go and see the return type of std::span::operator[], I only see a reference return, not a const reference return, while I was expecting a decltype(auto) for the return type.

Why do I not get an error that the operator with const reference is not implemented? How does the compiler figure out the correct answer?

When writing:

std::vector<double> vec{1.0,2.0};
std::span<const double> s(vec);
s[0]=1.0;

I get a compiler error, as expected:

Cannot assign to return value because function 'operator[]' returns a const value

However, when I go and see the return type of std::span::operator[], I only see a reference return, not a const reference return, while I was expecting a decltype(auto) for the return type.

Why do I not get an error that the operator with const reference is not implemented? How does the compiler figure out the correct answer?

Share Improve this question edited Mar 28 at 9:22 Jarod42 219k15 gold badges196 silver badges330 bronze badges asked Mar 27 at 20:29 RomainRomain 411 silver badge4 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 6

If the type of T is const double, then the return of T& is const double&.

The qualifiers, like const or volatile are part of the type that is held by the span, and are transitive to the returned reference of the operator[].

本文标签: cWhy does stdspanoperator not implement a const referenceStack Overflow