auto&x = const int *的类型是什么?
What the type is auto & x = const int *?
在一个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
中遗漏了什么吗?
请注意,对于auto& x
,您显式声明x
为引用;那么它的类型应该是const int *&
,即对指向const int
的指针的引用。
这是一个更好的主意(来自有效的现代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)
在发明的函数template <typename T> f(T);
中给T
的类型相同,对于auto&
和f(T&)
、const auto*
和f(const T*)
等也是如此。
因此,要从 Boost 获得正确答案,您需要声明:
template <typename T> void print_type(T&);
// ^^^^
x
的类型当然是const int*&
.
相关文章:
- 标准 N3337 5.2.10 第 7 条中的C++"类型"是什么意思?
- 如何声明一个标准::提升直方图的向量?提升直方图的类型是什么?
- 类名后跟括号的类型是什么
- std::chrono::duration::count函数的实际结果类型是什么
- c++运算符重载-我实际返回的操作数类型是什么
- 运算符和返回类型是什么意思?
- 指向 2D 数组的指针的类型是什么?
- RSA_verify中预期的数据类型是什么,无法验证从 Java 生成的签名
- 共享_ptr中多功能数组的类型是什么
- 构造函数的类型是什么?
- 字符串中单个字符作为数组的数据类型是什么
- 该结构继承的类型是什么
- 如果我获得Integer和Double的产品,输出的数据类型是什么
- C 中被视为可可的类型是什么
- 当函数采用右值引用时,函数中该变量的类型是什么?
- STD :: SETW,STD :: SETFILL等的真实返回类型是什么?
- 模板类中引用的引用的类型是什么
- const自动参考绑定到(NULL)指针 - 实际类型是什么
- 包含通过引用捕获的 lambda 函数的"variable"的类型是什么?
- 通过插座发送的内容的数据类型是什么