Home > Mobile >  Pass C function from class to another class object not from main
Pass C function from class to another class object not from main

Time:01-16

I have a class called CoffeeShop and another class called user. i want to pass a function from the class CoffeeShop to the user class but i have an error, what i tried to do is

User class:

class user {
public:
    function<void (string)> fun;
    string name;
    void order_coffee() {
        fun(name);
    }
};

then the coffeeshop class

class CoffeeShop {
public:
    mutex mtx;
    void Make_Coffee(string name) {
        cout << "in queue: " << name << endl;
        unique_lock<mutex> lock(mtx);
        cout << "welcome,order in process, " << name << endl;
        this_thread::sleep_for(chrono::seconds(4));
        cout << "good bye, " << name << endl;
        lock.unlock();
    }

    void assign() {
        user a;
        a.fun = CoffeeShop::Make_Coffee;
        a.name = "amr kamal";
        thread th1(&user::order_coffee, a);

        user b;
        b.fun = a.fun;
        b.name = "hadeer";
        thread th2(&user::order_coffee, b);

        th2.join();
        th1.join();
    }
};

I use the function assigned to start running the function, what i want to do is to let the users use the make_coffee function and wait in the queue and it process 1 by 1, i want to be able to let the users access the function.

i use the class as following in the main

int main() {
   CoffeeShop coffeeShop;
   coffeeShop.assign();
}

the Error i got is on assign the user make_coffee function

error C2679: binary '=': no operator found which takes a right-hand operand of type 'void (__cdecl CoffeeShop::* )(std::string)' (or there is no acceptable conversion)

CodePudding user response:

You have two options

  1. Wrap it in a lambda a.fun = [this](string line) {this->Make_Coffee(line);};
  2. Use std::mem_fun

The problem you are facing is that std::function needs to know about this. Also Why is "using namespace std;" considered bad practice?

  • Related