在main
函数中,我创建了一个const int
指针变量,将其赋值给auto&
声明的变量。然后使用decltype(x)
检查类型。我预计类型为const int*
。但is_same
会返回false
。
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
中的内容吗?
答案 0 :(得分: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;
^
你的辅助函数按值参数;类型推导中将忽略参数的引用,这就是你得到const int*
的原因。
答案 1 :(得分:4)
模板参数推导与auto
密切相关:声明auto x = e;
使x
与f(e)
在发明函数中赋予T
的类型相同template <typename T> f(T);
,同样适用于auto&
和f(T&)
,const auto*
和f(const T*)
等。
因此,要从Boost获得正确答案,您需要声明:
template <typename T> void print_type(T&);
// ^^^^
x
的类型当然是const int*&
。