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;
}

編譯結(jié)果:

<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++){,得到編譯結(jié)果

<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++){
      |                                     ~^~

第一種編譯結(jié)果只是類型不匹配,第二種編譯結(jié)果是auto自動(dòng)推導(dǎo)出錯(cuò)。這給我們?nèi)粘5木幊坦ぷ鲙硪恍┎槐恪?/p>

怎么辦?

這里借用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>>);

對(duì)于符號(hào)的std::size_t,使用z或者Z作為后綴。
對(duì)于無(wú)符號(hào)的std::size_t,使用z、Zu、U的集合,即uz、uZUz或者UZ。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容