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?
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With