dimanche 1 septembre 2019

why pass reference of a varaible to a varadic template function by universal reference operator (&&) failed?

I was intend to pass a reference of a variable into a member function pointer, which is a parameter of another varadic template function to invoke any kind of member function of a class, but from the printing result, it is not passed by reference, but just by value.

#include <functional>
#include <iostream>
#include <memory>

template <class WorkerType> class Delegate {
public:
  template <typename... Args>
  using WrkFunc = void (WorkerType::*)(Args... args);

  explicit Delegate(WorkerType &wrk) : m_worker(&wrk) {}

  template <typename... Args>
  void workerDo(WrkFunc<Args...> func, Args &&... args) {
    auto fn = std::bind(func, m_worker.get(), std::forward<Args>(args)...);
    fn();
  }

private:
  std::shared_ptr<WorkerType> m_worker;
};

class SomeWorker {
public:
  SomeWorker() = default;

  void doSomething(int &a) {
    a = 1000;
    std::cout << "2# address: " << &a << ", value: " << a << std::endl;
  }
};

int main() {
  SomeWorker wrk;
  Delegate<SomeWorker> del(wrk);
  int a = 0;
  std::cout << "1# address: " << &a << ", value: " << a << std::endl;
  del.workerDo(&SomeWorker::doSomething, a);
  std::cout << "3# address: " << &a << ", value: " << a << std::endl;
  return 0;
}


what I expected result like this:
1# address: 0x7fffc1dc621c, value: 0
2# address: 0x7fffc1dc621c, value: 1000
3# address: 0x7fffc1dc621c, value: 1000

but the actual result is:
1# address: 0x7fffc1dc621c, value: 0
2# address: 0x7fffc1dc61d0, value: 1000
3# address: 0x7fffc1dc621c, value: 0

Aucun commentaire:

Enregistrer un commentaire