类变量中类方法的列表/向量

二头肌

我需要维护将以不同顺序执行的方法列表以进行测试。我们正在从C转向C ++,以使用Google框架。是否可以维护一些指向要在类内部执行的类方法的函数指针,以便可以在实例化之后使用它们?请参考http://cpp.sh/265y

#include <iostream>
#include <string>
#include <vector>
using namespace std;

typedef void (*funcType)();

class Sample {
    public:
    vector<funcType> func_list;

    Sample();

    void formList();
    void method1();
    void method2();
    void method3();    
};

void Sample::formList() {
    func_list.push_back(&method1);
    func_list.push_back(&method2);
    func_list.push_back(&method3);
}

void Sample::method1 () {
    cout << "method1" << endl;
}

void Sample::method2 () {
    cout << "method2" << endl;
}

void Sample::method3 () {
    cout << "method3" << endl;
}

int main()
{
    Sample sample; //* = new Sample();
    sample.formList();
    vector<funcType>::iterator it;
    for (it = sample.func_list.begin(); it != sample.func_list.end(); ++it) {
         ((*it));
    }

}

答案:http//cpp.sh/8rr2

您可以使用可怕的指针到成员函数语法:

Live On Coliru

// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Sample;

typedef void (Sample::*funcType)();

class Sample {
  public:
    vector<funcType> func_list;

    Sample(){}

    void formList();
    void method1();
    void method2();
    void method3();
};

void Sample::formList() {
    func_list.push_back(&Sample::method1);
    func_list.push_back(&Sample::method2);
    func_list.push_back(&Sample::method3);
}

void Sample::method1() { cout << "method1" << endl; }

void Sample::method2() { cout << "method2" << endl; }

void Sample::method3() { cout << "method3" << endl; }

int main() {
    Sample sample; //* = new Sample();
    sample.formList();
    vector<funcType>::iterator it;
    for (it = sample.func_list.begin(); it != sample.func_list.end(); ++it) {
        (sample.*(*it))(); // HORRIFIC, INNIT? SEE BELOW FOR BETTER
    }
}

好多了:

但是,使用C ++ 11 / TR1std::function<>可以使您的用途更加广泛boost::function<>

typedef function<void(Sample*)> funcType;

// ...
func_list.push_back(mem_fn(&Sample::method1));
func_list.push_back(mem_fn(&Sample::method2));
func_list.push_back(mem_fn(&Sample::method3));

看到它Live On Coliru

for (it = sample.func_list.begin(); it != sample.func_list.end(); ++it) {
    (*it)(&sample); // much better
}

增加的多功能性主要在于您可以满足不同的签名: Live On Coliru

class Sample {
  public:
    vector<funcType> func_list;

    Sample(){}

    void formList();
    void method1(int);
    void method2(std::string);
    void method3(double, double, double);
};

void Sample::formList() {
    using std::placeholders::_1;
    func_list.push_back(bind(&Sample::method1, _1, 42));
    func_list.push_back(bind(&Sample::method2, _1, "Hello world"));
    func_list.push_back(bind(&Sample::method3, _1, 1, 2, 3));
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章