Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/158.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么按不同顺序使用std::remove_引用和std::remove_const会产生不同的结果?_C++_C++11_Templates_Typetraits - Fatal编程技术网

C++ 为什么按不同顺序使用std::remove_引用和std::remove_const会产生不同的结果?

C++ 为什么按不同顺序使用std::remove_引用和std::remove_const会产生不同的结果?,c++,c++11,templates,typetraits,C++,C++11,Templates,Typetraits,在以下代码中,我使用了std::remove_const和std::remove_reference,但在两种情况下使用的顺序不同,产生的结果不同: #include <iostream> #include <string> #include <vector> #include <iterator> #include <type_traits> using namespace std; int main() { vector

在以下代码中,我使用了
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;
}
查看

我的问题是为什么以不同的顺序使用
std::remove_const
std::remove_reference
会产生不同的结果?既然我正在删除引用和常量,那么结果不应该相同吗?

将只删除常量限定符(如果存在)。在
const std::string&
中,
const
不是顶级的,因此应用
remove\u const
对其没有影响

当您颠倒顺序并首先应用
remove_reference
时,结果类型为
const string
;现在
const
是顶级的,后续的
remove\u const
应用程序将删除
const
限定符。

将是一个很好的开始,它甚至有一个非常类似的示例,但带有指针。
First case : 
true
false
false

Second case : 
false
true
false