限制可以在C ++中传递给另一个函数的函数

时间:2013-12-06 08:14:29

标签: c++ static enums

我有一个包含几个非常相似的函数的类和一些其他函数,它们将这些函数作为输入交替使用。

一个更简单的例子:

class functions{
      public:
           int a();
           int b();
           int F(int (*f)() ); //f can only be a() or b()
};

在我把它们放到课堂上之前,我有类似

的东西
if(f!=a || f!=b) cout<<"error";

使用该类,它似乎变得更复杂,因为我相信我现在需要传递一个类实例或某些东西来摆脱我的error: invalid use of member function

我刚刚开始学习枚举列表,如果我处理普通变量,它似乎就能完成。我可以创建一个函数枚举吗?

限制可以传递给另一个函数的函数的最佳方法是什么?


我正在寻求静态强制转换方法,但仍需要int F(int(* f)())的帮助;

int functions::F(int (functions::*f)() )
{
    if(f==functions::a)  
        //gives  error: invalid operands of types 'int (functions::*)()' 
           //  and 'int (int(*)()' to binary operator =='

    int x=f();
        //gives error: must use ‘.*’ or ‘->*’ to call pointer-to-member
          //function in  'f(...)' 

    int y=(functions.*f)();
         //gives error: expected primary-expression before ‘.*’ token

     return 0;
}

2 个答案:

答案 0 :(得分:0)

这实际上取决于你想要达到的目标: 我在很大程度上说,这种限制最好通过代码审查而非编码来验证......

另一个解决方案是根本不使用该构造,并创建一个调用(私有)Fa()Fb()成员函数的a()b()函数。

问题的其余部分是&#34;我如何调用类的成员函数&#34; - 答案在很大程度上取决于Functions是否包含a()b()中使用的成员变量。如果没有成员函数,则将a()b()成员声明为static将起作用。另一方面,如果要使用&#34;成员函数指针&#34;,则语法分别为int (Functions::*f)&Functions::a,并且必须使用{的实例进行调用。 {1}}。因此,如果我们有Functions,您就会Functions fun。或fun.*f(),insice (*this).*f()

答案 1 :(得分:0)

您可以将接受的函数包装在一个类中:

#include <iostream>

class Functions
{
    public:
    int a() { return 0; }
    int b() { return 1; }
};

class Accept
{
    public:
    typedef int (Functions::*AcceptFunction)();
    int apply(Functions& object,  AcceptFunction function) {
        return (object.*function)();
    }
};


int main()
{
    Functions functions;
    Accept accept;
    std::cout << accept.apply(functions, &Functions::b) << std::endl;
}

(可以通过在Accept中将函数作为嵌套类来随意捆绑它)