Skip to content
Tags

, ,

Binding references

May 10, 2012

Suppose that you want to bind a reference to a variable to a function, then you can’t just pass the variable to the function bind, because that will copy the variable instead of taking a reference. Since a reference is not a first-class value, there is no way to pass the reference around. So instead you can use the function ref, which creates a reference wrapper around the variable. A reference wrapper is just an object which holds onto a reference, that way when the wrapper is copied, the reference is copied by the wrapper instead of the actual object.

For example, suppose you had a vector of int that you wanted to add up, one way to do that would be:

void
increment(int& i, int current)
{
  i += current;
}

int sumVector(const std::vector<int>& v)
{
  using std::placeholders::_1;
  int result = 0;
  for_each(v.begin(), v.end(), 
    std::bind(&increment, std::ref(result), _1));

  return result;
}
Advertisements

From → Library, Templates

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: