Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can placeholder be used with ref()

Tags:

c++

c++11

I am using c++11 features and just experimented the following code:

void dump(ostream &os, const MyType &mt)
{

}

void f(const vector<MyType> &mts, ostream &os)
{
   for_each(mts.begin(), mts.end(), bind(dump, ref(os), ref(_1));
}

This code compiles wrong at clang:

/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/stl_algo.h:4417:2: error: no matching function for call to object of type
      'std::_Bind<void (*(std::reference_wrapper<std::basic_ostream<char> >, std::reference_wrapper<const std::_Placeholder<1> >))(std::basic_ostream<char>
      &, const MyType &)>'
        __f(*__first);

If I strip ref from _1, it compile fine:

for_each(mts.begin(), mts.end(), bind(dump, ref(os), _1);

Seems like placeholder does not go with reference, but just like to confirm, can you list the semantic definition why it does not? Is it actually already passed by reference?

like image 369
my_question Avatar asked Mar 19 '23 12:03

my_question


1 Answers

std::ref() is used to pass values by reference that would otherwise be passed as copies.

In your code, it is used to pass os, a local name that obviously you don't want to copy.

Remember that it is the call to std::bind() that does the copy. That is, the value returned by std::bind() holds a copy of every passed object. std::ref() prevents that copy and keeps a reference instead.

But placeholders are not actually values inside the object returned by std::bind(). Instead, they are a mark that instruct the function to forward the n-th argument to the wrapped function. The key word here is forward: since the value is forwarded, it will be passed as reference if your function takes a reference, and as a copy if your function takes a copy.

Since the _1 is not the real value to be passed to the function, but instead a library trick to signal from where that value should be taken, using std::ref() with it makes no sense.

like image 64
rodrigo Avatar answered Mar 27 '23 14:03

rodrigo