成员函数返回指向成员函数的指针 [英] Member functions returning pointers to member functions

查看:62
本文介绍了成员函数返回指向成员函数的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个带有成员函数的类,该类将指向成员函数的指针返回.

I'd like to have a class with member functions that return pointers to member functions.

就是这样,

class Foo {
// typedef ????(Foo::* func)????
public:
   Func s1();
   Func s2();
   Func s3();
}

Func Foo::s1() {
  // do stuff
  return &Foo::s2;
}

Func Foo::s2() {
  // do stuff
  return &Foo::s3;
}

Func Foo::s3() {
  // do stuff
  return 0;
}

基本上,我想做的是实现一个状态机,其中每个状态现在是下一个状态,并通过函数指针将其返回.

Basically, what I try to do is to implement a state machine, where each state nows the next state and returns it by means of a function pointer.

注意:我对实现状态机的其他方式不感兴趣.我真的很想知道它是否可以按照上面的方式实现.

Note: I'm not interested in other ways of implementing a state machine. I really like to know if it can be implemented in a way that looks like the above.

上下文:我从这次演讲中得到了启发: http://www.youtube.com/watch?v = HxaD_trXwRE ,想知道在C ++中是否可以使用类似的模式.

Context: I got inspired by this talk: http://www.youtube.com/watch?v=HxaD_trXwRE and wondered if a similar pattern can be used in C++.

推荐答案

GotW 并将其调整为成员函数:

Blatently ripping off the solution at GotW and adapting it to member functions:

class Foo {
  public:
    struct FuncPtrRet;
    typedef FuncPtrRet(Foo::*FuncPtr)();
    struct FuncPtrRet {
        FuncPtrRet(FuncPtr pp) : p(pp) { }
        operator FuncPtr() { return p; }
        FuncPtr p;
    };
    FuncPtrRet s1() { return &Foo::s2; }
    FuncPtrRet s2() { return &Foo::s3; }
    FuncPtrRet s3() { return &Foo::s3; }
};

int main() {
    Foo test;
    Foo::FuncPtr state = test.s1();
    state = (test.*state)();
    state = (test.*state)();
    state = (test.*state)();
    state = (test.*state)();
    state = (test.*state)();
    return 0;
}

这似乎适用于Clang 3.3.我认为对于空闲状态(此处为s3),返回0不是一个好的选择,但是在那里我可能是错的.对我来说,拥有一个返回自己的空闲状态似乎更直观.

This seems to work on Clang 3.3. I don't think returning 0 is a good choice for an idle state (s3 here), but I might be wrong there. Having an idle state that returns itself seems more intuitive to me.

这篇关于成员函数返回指向成员函数的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆