lundi 23 mai 2016

Passing reference_wrapper objects as function arguments in C++11

How does one pass and operate on constant (or non constant) references inside STL containers. Say I have a function:

bool foo(const Obj& A, const Obj& B) {
  // do some computation on A & B
}

and since A & B always occur together, I would like to put them in an STL pair:

bool foo(const  std::pair<Obj, Obj>& A_and_B) {
  // do some computation on A & B
}

However now both objects A & B get copied into a pair every time foo needs to be called. Looking around I found reference_wrapper in C++11. Though doing something like this doesn't quite work:

bool foo(const  std::pair<std::reference_wrapper<Obj>, std::reference_wrapper<Obj>>& A_and_B) {
  // do some computation on A & B
}

bool foo(const  std::pair<Obj, Obj>& A_and_B) {
  foo(std::make_pair(std::ref(A_and_B.first), std::ref(A_and_B.second)));
}

What is the correct way of passing containers with reference values without using pointers?

Aucun commentaire:

Enregistrer un commentaire