Std :: bind on member with call operator

It may be silly and silly, but I would like to understand what is going on here.

I have the following code:

#include <iostream>
#include <functional>

namespace
{
    struct call
    {
        void operator()() const
        {
            std::cout << "call::operator()" << std::endl;
        }
    };

    struct dummy
    {
        dummy() = default;
        dummy(const dummy&) = delete;

        call member;
    }; 
}

      

Thus, a member will essentially work like any other method on the object, allowing it to be called like:

dummy d;
d.member()

      

To print call::operator()

.

Now I would like to use bind for this, the initial implementation looked like this:

int main() 
{
    dummy d;

    auto b = std::bind(&dummy::member, &d);
    b();
    return 0;
}

      

This compiles, but nothing is printed. I really don't understand what's going on - the fact that it compiles but doesn't create any puzzles to output me :) Surely there is some magic going on inside the belly std::bind

, but what?

Here is a link to play with the code: https://ideone.com/P81PND

+3


source to share


2 answers


Your binding is currently returning a member, so b()

- d.member

. You need to call operator ():

b()(); // call::operator()

      



Alternatively, you can use any of:

b = std::bind(&call::operator(), &d.member);
b = [&]() {d.member();};

      

+6


source


You can also call via std::reference_wrapper

. No need at bind

all.



int main() 
{
    dummy d;

    auto b= std::cref(d.member);  // create reference wrapper
    b();
    return 0;
}

      

0


source







All Articles