2017-10-19 130 views
3

main函數中,我創建了一個變量const int指針,將其指定給由auto&聲明的變量。然後使用decltype(x)來檢查類型。我預計這種類型是const int*。但是is_same返回false什麼類型是auto&x = const int *?

int main() 
{ 
    int a = 10; 
    const int * cp_val= &a; 
    auto& x = cp_val; 
    bool is_const_int_ptr = std::is_same<decltype(x), const int *>::value; // returns 0 

    // *x = 100; // error: assignment of read-only location '* x' 
} 

但是,如果我添加下面的輔助函數:

#include <boost/type_index.hpp> 

template<typename T> 
void print_type(T) 
{cout << "type T is: "<< boost::typeindex::type_id_with_cvr<T>().pretty_name()<< '\n';} 

在主,我調用函數

print_type(x); // It returns int const* 

我缺少的東西std::is_same

回答

4

模板參數推導和auto是密切相關的:聲明auto x = e;x同一類型f(e)會給T在發明功能template <typename T> f(T);,同樣爲auto&f(T&),​​和f(const T*)

因此,要獲得Boost的正確答案,您需要聲明:

template <typename T> void print_type(T&); 
//         ^^^^ 

The ty x的pe當然是const int*&

6

請注意,對於auto& x,您明確聲明爲x作爲參考;那麼它的類型應該是const int *&,即對指向const int的指針的引用。

這是一個比較好的主意(從Effective Modern C++(Scott Meyers))在編譯時從編譯錯誤消息中獲取準確類型。

template <typename> 
struct TD; 

然後用它作爲

TD<decltype(x)> td; 

,你會得到錯誤消息像

source_file.cpp:15:21: error: implicit instantiation of undefined template 'TD<const int *&>' 
    TD<decltype(x)> td; 
        ^

LIVE

您的輔助函數的值取參數;在類型推演中,參數的參考性將被忽略,這就是爲什麼你得到了const int*

相關問題