简体   繁体   English

const限定词到decltype

[英]const qualifier to decltype

My first try of using decltype 我第一次尝试使用decltype

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

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

doesn't compile, complaining about assigning to read-only variable ptr . 无法编译,抱怨分配给只读变量ptr What I'm trying to achieve is ptr to be of type const int* . 我想要实现的是ptrconst int*类型。 How can I make it work? 我该如何运作? Thanks. 谢谢。

std::vector has a const_pointer typedef. std::vector具有const_pointer typedef。 You can use that like 你可以这样使用

decltype(vals)::const_pointer ptr;

to get the correct const pointer to the vector type ( Live Example ). 以获得指向向量类型的正确const指针( 实时示例 )。

Just don't declare the pointer before you need it. 只是不要在需要之前声明指针。 Then you can deduce its type (in this case, the desired const int* ) in the initialization. 然后,您可以在初始化时推导其类型(在这种情况下,为所需的const int* )。

This works: 这有效:

std::vector<int> val {1,2,3,4};

for (const auto &v : val) {
    auto p = &v;
    std::cout << *p;
}

This fails: 这将失败:

std::vector<int> val {1,2,3,4};

for (const auto &v : val) {
    auto p = &v;
    *p = 7;
}

Your declaration of ptr is basically const (int *) ptr , or int * const ptr . 您对ptr声明基本上是const (int *) ptrint * const ptr So the pointer is constant, not the objects it points to. 因此,指针是常量,而不是它指向的对象。 You can either make vals const , or at least cast it to const inside the decltype , or use std::vector 's typedefs instead of decltype . 您可以将vals设为const ,或者至少将其decltypedecltype内的const ,或者使用std::vector的typedefs代替decltype

typedef is not textual substitution. typedef不是文本替换。 decltype is not textual substitution. decltype不是文本替换。 The modifier const applies to the entire thing it's applied to, it doesn't reach inside the result of decltype to change the left-most thing. 修饰符const适用于它所应用的整个对象,它不会到达decltype的结果内部来更改最左边的对象。

This would work though, because now const is applied to the element type to make the type (const int) , and then ptr is made a pointer to that: 但是这将起作用,因为现在将const应用于元素类型以使其成为类型(const int) ,然后将ptr用作指向该类型的指针:

const std::remove_reference<decltype(vals[0])>::type * ptr;

Note that this one wouldn't work, since it uselessly tries to const -qualify a reference type: 请注意,这是行不通的,因为它无用地尝试const -qualify引用类型:

std::add_pointer<const decltype(vals[0])>::type ptr;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM