I have a class with a private member std::set<Segment*> mSegments
and the following method:
std::pair<iterator, iterator> getSegments() {
return boost::tie(mSegments.begin(), mSegments.end());
}
and I get the following error:
invalid initialization of non-const reference of type
std::_Rb_tree_const_iterator<Segment*>&
from a temporary of typestd::_Rb_tree_const_iterator<Segment*>
I'm not sure how to solve this one. Can anyone tell me what the problem is?
I think that your problem is that you should probably be using make_pair
here instead of tie
. The point of tie
is to allow functions that return tuples to have the return value assigned to multiple values at once. For example, if Get3DPoint
returns a tuple<int, int, int>
, then you could write
int x, y, z;
tie(x, y, z) = Get3DPoint();
Because of this, tie
always accepts its parameters by non-const
reference so that they can be mutated. In your case, the return values of begin()
and end()
are temporaries, so they can't be bound to non-const
references.
make_pair
(and make_tuple
), on the other hand, are designed to take multiple values and package them up into a single pair
or tuple
object that can be passed around. This is what you want to use in your function. If you change the code to read
std::pair<iterator, iterator> getSegments() {
return std::make_pair(mSegments.begin(), mSegments.end());
}
Then your code should compile just fine.
Hope this helps!
I don't have much experience with boost::tie
but by looking at the error message I can say that the error is because you are trying to bind a temporary to a non-const reference.
Temporaries cannot be bound to references to non-const objects.
For example
Myclass &ref = Myclass(); // ill formed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With