2017-10-19 5 views
3

main 함수에서 으로 선언 된 변수에 const int 포인터 변수를 할당했습니다. 그런 다음 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&), const auto*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*입니다.

관련 문제