2017-04-17 33 views
21

请注意,我用std::thread只是在错误得到可读类型:为什么不std :: remove_const删除const限定符?

int main() { 
    const int * first; 
    using deref = decltype(*first); 
    std::thread s = std::remove_const<deref>::type{}; // const int ??? 
    std::thread s2 = deref{}; // const int 
    std::thread s3 = std::remove_const<const int>::type{}; // int 
} 

看起来好像remove_const<deref>::typeconst int,不可更改int,因为我期望的那样。

+3

你的标题说'remove_reference',但你不用它在你的身体。 –

+0

tnx,固定,正在使用两个原始代码,所以我混淆了:) – NoSenseEtAl

+4

我会建议你使用[this](http://coliru.stacked-crooked.com/a/bfccfe0a5508f107)来显示类型而不是你的'std :: thread'方法,因为它显示的实际类型是'const int&',而你的方法在于你并显示'const int'。 – nwp

回答

30

注意*first是左值表达,那么decltype(*first)结果类型将是const int&,即,const int的参考。参考不是const本身(它不能是const限定的,没有像int& const这样的东西),使用std::remove_const就会产生相同的类型,即const int&

参见decltype specifier

3)如果参数为T类型的任何其他表达,和

b)如表达式的值类是左值,然后decltype产量 T&;

您可以用std::remove_reference使用std::remove_const在一起:

std::remove_const<std::remove_reference<deref>::type>::type // -> int 
             ~~~~~    // -> const int & 
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  // -> const int 

BTW:

请注意,我用std::thread只是在错误得到可读类型:

请注意,它没有给出这种情况下的正确类型。下面是来自Effective Modern C++ (Scott Meyers)这个类模板帮手:

template<typename T> 
class TD; 

,并用它作为

TD<deref> td; 

你会得到包含deref类型的错误消息,例如从clang

prog.cc:16:11: error: implicit instantiation of undefined template 'TD<const int &>' 
TD<deref> td; 
     ^
+2

Aaa,这就是为什么你应该写'int const&'而不是'const int',那么问题的答案是显而易见的。 – Mehrdad

相关问题