[英]Why does using std::remove_reference and std::remove_const in different order produce different results?
在下面的代碼中,我使用了std::remove_const
和std::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
我的問題是為什么以不同的順序使用std::remove_const
和std::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.