c++ - decltype 的 const 限定符

标签 c++ c++11

我第一次尝试使用decltype

vector<int> vals;
const decltype(&vals[0]) ptr;

for (const auto& val : vals)
    ptr = &val;    

不编译,提示分配给只读变量 ptr。我想要实现的是 ptrconst int* 类型。我怎样才能让它发挥作用?谢谢。

最佳答案

std::vector 有一个 const_pointer typedef。你可以像这样使用它

decltype(vals)::const_pointer ptr;

获取指向 vector 类型 (Live Example) 的正确常量指针。

关于c++ - decltype 的 const 限定符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38127764/

相关文章:

c++ - C++ 中全局数组初始化时的语法和缺少类型说明符错误

c++ - Fstream 作为私有(private)成员访问

performance - 1000 万个输入的合并排序

c++ - 使用什么来存储 Unicode (UTF-16) 字符串? (C++11)

c++ - 静态函数作为类模板参数 - 导致可维护性问题

c++ - 为什么额外的 -I 标志(包含目录)会中断编译? (使用英特尔编译器)

c++ - 带有 Protocol Buffer 的程序无法使用 MinGW-w64 : "undefined reference to google::protobuf::..." 进行编译

c++ - 如何使用 std::get 在元组上赋值?

c++ - 依赖名称和范围

c++ - 使用英特尔线程构建模块 : error operands to ? 进行编译: