c – 使用std :: function来包装非静态成员函数指针
发布时间:2020-12-16 10:02:19 所属栏目:百科 来源:网络整理
导读:我最近宣布了类似的类: class Foo {public: void run();private: void foo(); void boo(); void doo(); std::functionvoid()getFunction(int);}; 在这个例子中,我想根据传递的整数获得指向成员函数的指针. void Foo::run(){ std::functionvoid() f; for(int
我最近宣布了类似的类:
class Foo { public: void run(); private: void foo(); void boo(); void doo(); std::function<void()>getFunction(int); }; 在这个例子中,我想根据传递的整数获得指向成员函数的指针. void Foo::run(){ std::function<void()> f; for(int i = 0; i < 3; i++){ f = getFunction(i); f(); } } std::function<void()>Foo::getFunction(int i){ switch(i){ case 0: return foo; case 1: return Foo::boo; case 2: return this->*doo; } } 所有情况都会导致编译器错为案例1添加静态功能,但我不想使用静态成员. 有没有办法在不使用static关键字的情况下正确获取这些指针? 解决方法
作为宋元瑶的答案的延伸
怎么用lambdas? (假设它只是能够调用内部函数而不是函数指针本身很重要) void Foo::run(){ std::function<void()> f; for(int i = 0; i < 3; i++){ f = getFunction(i); f(); } } std::function<void()> Foo::getFunction(int i) { switch(i){ case 0: return [this](){this->foo();}; case 1: return [this](){this->boo();}; case 2: return [this](){this->doo();}; } } LIVE3 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |