这是我的精简程序,我试图在运行时使用函数变量来修改类的功能。所以-我使用std::function模板声明了一个成员变量m_func,并用兼容的签名声明了一个函数myFunc:
#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);
}然而,编译器(带-std=c++11选项的g++ 4.8.4 )给我一个长输出的错误,告诉我template argument deduction/substitution failed和更多...
为什么不能将myFunc函数赋给m_func变量?
发布于 2017-02-22 05:46:27
void assign() {m_func = &T::myFunc;}成员函数指针有一个隐式的this指针,需要将其作为签名中的第一个参数传递。要么先使用std::bind绑定它,
void assign() {
m_func = std::bind(&T::myFunc, this, std::placeholders::_1);
}或者使用lambda表达式(捕获this)。
void assign() {
m_func = [this](int arg){ return this->myFunc(arg); };
}发布于 2017-02-22 05:45:59
不能将非静态成员函数指针直接赋给std::function。这个问题的一般解决方案是将this指针绑定到一个lambda中,如下所示:
void assign() {
m_func = [this](int N) {
return this->myFunc(N);
};
}在您的例子中,将myFunc设为静态似乎更简单。
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;
};发布于 2017-02-22 05:41:44
如果希望在当前对象上调用成员函数,则需要:
m_func = std::bind(&T::myFunc, this, std::placeholders::_1);https://stackoverflow.com/questions/42378499
复制相似问题