最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - Why does std::span::operator[] not implement a const reference? - Stack Overflow

programmeradmin2浏览0评论

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[].

发布评论

评论列表(0)

  1. 暂无评论