C++23: std::size_t 字面值常量

为什么?

举例:

#include <iostream>
#include <vector>
int main(){
    std::vector<int> vec{1, 2, 3};
    for(auto i = 0; i<vec.size(); i++){
        std::cout<<vec[i]<<std::endl;
    }
    return 0;
}

编译结果:

<source>: In function 'int main()':
<source>:8:22: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
    8 |     for(auto i = 0; i<vec.size(); i++){
      |                     ~^~~~~~~~~~~

或者,我们将for(auto i = 0; i<vec.size(); i++){改成for(auto i = 0, s = vec.size(); i<s; i++){,得到编译结果

<source>: In function 'int main()':
<source>:8:9: error: inconsistent deduction for 'auto': 'int' and then 'long unsigned int'
    8 |     for(auto i = 0, s = vec.size(); i<s; i++){
      |         ^~~~
<source>:8:38: warning: comparison of integer expressions of different signedness: 'int' and 'long unsigned int' [-Wsign-compare]
    8 |     for(auto i = 0, s = vec.size(); i<s; i++){
      |                                     ~^~

第一种编译结果只是类型不匹配,第二种编译结果是auto自动推导出错。这给我们日常的编程工作带来一些不便。

怎么办?

这里借用cppreference的例子:

static_assert(std::is_same_v<decltype(0UZ), std::size_t>);
static_assert(std::is_same_v<decltype(0Z), std::make_signed_t<std::size_t>>);

对于符号的std::size_t,使用z或者Z作为后缀。
对于符号的std::size_t,使用zZuU的集合,即uzuZUz或者UZ

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容