2017-04-17 29 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

相關問題