在向量中存储特定类的成员函数的语法是什么?

What is the syntax for storing a specific class's member functions in a vector?

本文关键字:成员 函数 是什么 语法 向量 存储      更新时间:2023-10-16

我做了相当多的搜索,但是*()和类作用域的组合极大地阻碍了我对语法的理解,每次编辑都会抛出一个新的错误,有什么帮助吗?

我想做什么:

声明一个指向MyClass.h

中成员函数指针的std::vector

将实际成员函数赋值给MyClass.cpp构造函数中的std::vector

成员函数不是static

谢谢!

我很好奇你将从哪里使用它们。您可以看到,为了调用一个c++类成员函数,您需要有一个实例指针来调用它(每个成员函数都需要一个this来访问类状态)。通常你会用std::bind将成员函数指针和实例指针包装在一起,然后可能将结果存储在std::function中。要把它们化成向量,它们都需要相同的签名。

这是你要找的东西吗?

class P
{
    typedef std::function<void (void)> func_t;
    std::vector<func_t> functions;
public:
    P()
    {
        functions.push_back(std::bind(&P::foo1, this));
        functions.push_back(std::bind(&P::foo2, this));
        functions.push_back(std::bind(&P::foo3, this));
    }
    void foo1(void)
    {
        std::cout << "foo1n";
    }
    void foo2(void)
    {
        std::cout << "foo2n";
    }
    void foo3(void)
    {
        std::cout << "foo3n";
    }
    void call()
    {
        for(auto it = functions.begin(); it != functions.end(); ++it)
        {
            (*it)();
        }
    }
};
int main()
{
    P p;
    p.call();
}

在OP进一步澄清后,我将提出以下建议:

class P
{
    typedef std::function<void (void)> func_t;
    std::map<const char*, func_t> functions;
public:
    P()
    {
        functions["foo1"] = std::bind(&P::foo1, this);
        functions["foo2"] = std::bind(&P::foo2, this);
        functions["foo3"] = std::bind(&P::foo3, this);
    }
    void foo1(void)
    {
        std::cout << "foo1n";
    }
    void foo2(void)
    {
        std::cout << "foo2n";
    }
    void foo3(void)
    {
        std::cout << "foo3n";
    }
    void call_by_name(const char* func_name)
    {
        functions[func_name]();
    }
};
int main()
{
    P p;
    p.call_by_name("foo1");
    p.call_by_name("foo2");
    p.call_by_name("foo3");
}

可以像这样使用成员函数指针(c++ 11与这部分无关):

struct S {
   int foo(){std::cout<<"foo"; return 0;}
   int bar(){std::cout<<"bar"; return 0;}
};
int main() {
   std::vector<int(S::*)()> funcs{&S::foo, &S::bar};
   S s;
   for (auto func : funcs) {
      (s.*func)();
   }
}

然而,如果你使用c++ 11, std::function可以使它更简洁:

std::vector<std::function<int(S &)>> funcs{&S::foo, &S::bar};
S s;
for (auto func : funcs) {
   func(s);
}

如果您使用c++ 03, Boost有boost::function,这是类似的