Is it possible to cast a pair<Key, Value> to a pair<const Key, Value>?

百般思念 提交于 2019-11-30 21:40:05

You can convert a value of type pair<Key,Value> to pair<const Key,Value>.

However, reading the question carefully, you're actually asking if, given a pair<Key,Value> you can create a pointer or reference to pair<const Key,Value> referring to the same object.

The answer is no - the only situation where a reference or pointer to one type can refer to an object of a different type is if the object type inherits from the referenced type.

One possibility is to return a pair of references, pair<const Key&, Value&>, created from the pair you wish to reference.

Yes.

std::pair<int, double> p(1,2);
std::pair<const int, double> q = p;   // no problem

//q.first = 8;  // error
q.second = 9;

int b; double d;
std::pair<int &, double &> s(b,d);
std::pair<int const &, double &> t = s;  // also fine

As Kerrek SB pointed out, you can construct std::pair<const Key, Value> from std::pair<Key, Value>. However, your original question implies that you want to avoid constructing std::pair objects each time your iterator is dereferenced.

Unfortunately, there is not a good way to do this. You may have to construct the pair object and actually store it somewhere, particular for operator->. Otherwise you have to be able to have your map actually store pair<const Key, Value> to be able to return references/pointers to it from your iterator. Basically to return a reference/pointer, it has to be stored somewhere in that form: it cannot be a temporary.

Avoid the const_cast. That's just asking for undefined behavior when you use it to cast pair this way even though it may work quite often.

I met exactly the same problem. My solution was to create a new map object as part of the iterator class, then add to it members that are missed in the upstream map class and return the reference to members of it. Not very efficient, but works.

Your solution have two issues:

  1. Assigning a const variable with const_cast is undefined behavior. The compiler optimisations could provide strange results.
  2. Any new dereference would invalidate the results of previous dereference. It should not to. So, depending of the usage of your iterator it may also produce strange results.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!