什么类型是auto&x = const int *?
问题描述:
在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
?
答
模板参数推导和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*&
。
答
请注意,对于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*
。