2017-10-19 9 views
3

main関数では、const intポインタの変数を作成し、auto&で宣言された変数に割り当てます。次に、decltype(x)を使用してタイプを確認します。私はそのタイプがconst int*であると予想しました。しかしis_samefalseを返します。タイプは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;f(e)同じタイプauto&f(T&)、​​とf(const T*)についても同様に発明関数template <typename T> f(T);Tに与える、となるx与える、等

したがって、Boostから正解を得るには、次のように宣言する必要があります。

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

ty xのpeはもちろんconst int*&である。

6

auto& xについては、xを参照として明示的に指定しています。そのタイプはconst int *&でなければならず、すなわちconst intへのポインタへの参照でなければならない。

コンパイルエラーメッセージからコンパイル時に正確なタイプを取得するために、より良いアイデアがあります(Effective Modern C++(Scott Meyers))。

template <typename> 
struct TD; 

、あなたは

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

LIVE

あなたのヘルパー関数は、値によってパラメータを取るようなエラーメッセージが表示されます

TD<decltype(x)> td; 

としてそれを使用します。引き数の参照は型減算で無視されるので、const int*が得られます。

関連する問題