c++ - 为什么以不同的顺序使用 std::remove_reference 和 std::remove_const 会产生不同的结果?

标签 c++ c++11 templates typetraits

在下面的代码中,我使用了 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只会删除 top-level const 限定符,如果存在的话。在 const std::string& 中,const 不是顶级的,因此应用 remove_const 对其没有影响。

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

关于c++ - 为什么以不同的顺序使用 std::remove_reference 和 std::remove_const 会产生不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30690269/

上一篇:c++ - 安全阵列删除

下一篇:c++ auto 多选

相关文章:

用于删除和重置指针的 C++ 模板函数

c++ - 让本地符号走向全局

c++ - Phong-Alpha Material 透明度

c++ - T和T&的区别?

c++ - 尝试使用 dynamic_cast 时出现 "source type is not polymorphic"

c++ - C++ 中的 strchr 在哪里?

c++ - 函数模板的多个实例与参数列表匹配

c++ - std::map<key_type, value_type>::find(different_key_type)

c++ - bufferedPercent 是如何工作的

c++ - 参数包函数参数可以默认吗?