In the following code I have used std::remove_const
and std::remove_reference
but in different order in two cases which are giving different results:
#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;
}
The output is:
First case :
true
false
false
Second case :
false
true
false
Check on Coliru Viewer
My question is why does using std::remove_const
and std::remove_reference
in different order produce different results? Since I am removing both reference and const
-ness, shouldn't the result be the same?
remove_const
will only remove a top-levelconst
qualifier, if one exists. Inconst std::string&
, theconst
is not top-level, hence applyingremove_const
has no effect on it.When you reverse the order and apply
remove_reference
first, the resulting type isconst string
; now theconst
is top-level and the subsequent application ofremove_const
will remove theconst
qualifier.