簡體   English   中英

為什么以不同的順序使用std :: remove_reference和std :: remove_const會產生不同的結果?

[英]Why does using std::remove_reference and std::remove_const in different order produce different results?

在下面的代碼中,我使用了std::remove_conststd::remove_reference但在兩種情況下以不同的順序給出了不同的結果:

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <type_traits>

using namespace std;

int main()
{
    vector<string> ar = {"mnciitbhu"};
    cout<<boolalpha;
    cout<<"First case : "<<endl;
    for(const auto& x : ar)
    {
        // Using std::remove_const and std::remove_reference
        // at the same time
        typedef typename std::remove_const<
            typename std::remove_reference<decltype(x)>::type>::type TT;
        cout<<std::is_same<std::string, TT>::value<<endl;
        cout<<std::is_same<const std::string, TT>::value<<endl;
        cout<<std::is_same<const std::string&, TT>::value<<endl;
    }
    cout<<endl;
    cout<<"Second case : "<<endl;
    for(const auto& x : ar)
    {
        // Same as above but the order of using std::remove_reference
        // and std::remove_const changed
        typedef typename std::remove_reference<
            typename std::remove_const<decltype(x)>::type>::type TT;
        cout<<std::is_same<std::string, TT>::value<<endl;
        cout<<std::is_same<const std::string, TT>::value<<endl;
        cout<<std::is_same<const std::string&, TT>::value<<endl;
    } 
    return 0;
}

輸出是:

First case : 
true
false
false

Second case : 
false
true
false

檢查Coliru Viewer

我的問題是為什么以不同的順序使用std::remove_conststd::remove_reference產生不同的結果? 既然我要刪除引用和const -ness,結果應該不一樣嗎?

remove_const只會刪除頂級 const限定符(如果存在)。 const std::string&const不是頂級的,因此應用remove_const對它沒有影響。

當您顛倒順序並首先應用remove_reference ,結果類型是const string ; 現在const是頂級的,隨后的remove_const應用程序將刪除const限定符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM