4

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 type std::_Rb_tree_const_iterator<Segment*>

I'm not sure how to solve this one. Can anyone tell me what the problem is?

4 Answers 4

5

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-constreference 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!

Sign up to request clarification or add additional context in comments.

Comments

3

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 

Comments

0

boost::tie's parameters are non-const references, but begin and end return temporaries. You'd need to store them somewhere for that to work.

Comments

0

This is declaration of tie:

template <class A, class B> tied<A,B> tie(A& a, B& b); 

And this is declaration of begin (end):

iterator begin() 

This means that begin() returns temporary object (not reference to it) which can't passed to tie.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.