在下面的代码中,我使用了
输出结果为:
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
在Coliru Viewer上检查一下。
我的问题是,为什么使用 std::remove_const
和 std::remove_reference
的顺序不同会产生不同的结果?因为我正在删除引用和 const
,所以结果不应该是相同的吗?