auto & x = const int * 是什么类型?
What the type is auto & x = const int *?
在一个main
函数中,我创建了一个const int
指针的变量,并将其赋值给auto&
声明的变量。然后使用 decltype(x)
检查类型。我预计类型是 const int*
。但是 is_same
returns 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
中的内容?
请注意,对于 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*
.
模板参数推导和 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*&
.
在一个main
函数中,我创建了一个const int
指针的变量,并将其赋值给auto&
声明的变量。然后使用 decltype(x)
检查类型。我预计类型是 const int*
。但是 is_same
returns 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
中的内容?
请注意,对于 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*
.
模板参数推导和 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*&
.