Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign member function to a member variable, defined using std::function? [duplicate]

Tags:

c++

This is my stripped-down program, where I'm trying to use function variables to modify class functionality at run time. So - I declare a member variable m_func using the std::function template and a function myFunc with compatible signature:

#include <functional>
#include <iostream>

struct T
{
  T():m_func([](int){return true;}) {}
  void assign() {m_func = &T::myFunc;}    // <======== Problem is here
  void call(int M) const {std::cout << m_func(M) << std::endl;}
private:
  bool myFunc(int N) {return (N >= 4);}
  using func = std::function<bool(int)>;
  func m_func;
};

int main()
{
  T t;
  t.assign();
  t.call(6);
}

However, the compiler (g++ 4.8.4 with -std=c++11 option) gives me an error with long output, saying that template argument deduction/substitution failed and a lot more...

Why can't I assign the myFunc function to the m_func variable?

like image 615
HEKTO Avatar asked Sep 20 '25 16:09

HEKTO


1 Answers

A non-static member function pointer cannot be assigned to std::function directly. The general solution for this problem is to bundle the this pointer into a lambda like this :

void assign() { 
    m_func = [this](int N) { 
        return this->myFunc(N); 
    };
}

In your case, it seems simpler to just make myFunc static.

struct T
{
    T() :m_func([](int) {return true; }) {}
    void assign() { m_func = &T::myFunc; }
    void call(int M) const { std::cout << m_func(M) << std::endl; }
private:
    static bool myFunc(int N) { return (N >= 4); }
//  ^^^^^^ static methods can be assigned to std::function directly
    using func = std::function<bool(int)>;
    func m_func;
};
like image 156
François Andrieux Avatar answered Sep 22 '25 06:09

François Andrieux