Search code examples
c++boost-bindboost-function

binding to boost::function class member compilation error


boost::function<void()> test_func;

struct test_t
{
   boost::function<void(int)> foo_;

   void test()
   {
      // This works as expected
      test_func = boost::bind(test_t::foo_, 1);
   }

};

int main(int argc, _TCHAR* argv[])
{
      test_t test;

      test.test();

      // error C2597: illegal reference to non-static member 'test_t::foo_'
      test_func = boost::bind(test_t::foo_, &test, 1);

      const auto a = 0;

   return 0;
}

What the problem with the code? Why code test_func = boost::bind(test_t::foo_, &test, 1); compiles in test_t::test() and gives me the error in main()?

Thank you


Solution

  • That's because inside a method test_t::foo_ refers to this->foo_, while test_t::foo_ in main could refer to foo_ only if it was a static member of that class. You need to write test.foo_ there instead.