【问题标题】:pointer on method as an argument方法上的指针作为参数
【发布时间】:2013-05-30 01:24:57
【问题描述】:

为避免代码重复,我试图将指向函数的指针作为静态方法的参数传递。

我有一个只有静态方法的类 (Geo)。其中一种方法 (+++Geo::traceRay(+++)) 应该只显示(Geo::display(+++)) 一些东西,然后返回一个 int。

另一个类 (Las) 需要使用 Geo::traceRay(+++) 方法,但应该显示(Las::display(+++)) 其他东西。 因此,我尝试将指向函数参数的指针传递给 Geo::traceRay(+++, pointer to function) 方法。指向的函数将正确的“display()”方法。

到目前为止,将第一个指针传递给 display() 不是问题,但我找不到如何处理第二个。

class Geo
{
public:
    static bool display(int pix);
    static int traceRay(int start, int end, bool (*func)(int) = &Geo::display); // no issue with this default parameter
};


class Las
{
public:
    bool display(int pix);
    void run();
};


int Geo::traceRay(int start, int end, bool (*func)(int))
{
    for (int i = start; i < end ; ++i )
    {
        if((*func)(i)) return i;
    }
    return end;
}

bool Geo::display(int pix)
{
    cout << pix*100 << endl;
    return false;
}


bool Las::display(int pix)
{
    cout << pix << endl;
    if (pix == 6) return true;
    return false;
}

void Las::run()
{
    bool (Las::*myPointerToFunc)(int) = &display;       // I can just use display as a non member class, but it should stay a member
    Geo::traceRay(0,10, myPointerToFunc);               // issue here!
}


int main()
{
    Geo::traceRay(0,10); // use the "normal display" = the default one// OK

    Las myLas;
    myLas.run();

    return 0;
}

【问题讨论】:

    标签: c++ function-pointers


    【解决方案1】:

    您不能将成员函数指针作为函数指针传递。我认为制作Las::display static 不是一种选择。在这种情况下,我建议使用std::function 并使用std::bind 绑定当前实例:

    static int traceRay(int start, int end, std::function<bool(int)> func = &Geo::display);
    ...
    Geo::traceRay(0,10, std::bind(&Las::display, this, std::placeholders::_1));
    

    另外,在这两种情况下,您都可以通过以下方式致电func:

    func(i);
    

    无需先取消引用。

    【讨论】:

    • 非常感谢您的回答。我不知道std::function 和std::bind。我需要link 来了解它是如何工作的,但现在我得到了我想要的。此外,要从 Las 类调用 Geo::traceRay,您必须使用 Geo::traceRay(0,10, std::bind(&amp;Las::display, this, std::placeholders::_1));
    【解决方案2】:

    Chris 的建议是非常棒的,如果它可以做到的话。

    如果您有多个类似的共享函数,则另一种方法是使用具有两个实现的接口(使用虚拟方法 Display(+++)),将实现的实例放在Geo 和 Las 中的每个问题(或 Las 可以直接实现接口)。然后 traceRay 获取接口基类的引用,并在其上调用 display 方法。

    【讨论】:

      猜你喜欢
      • 2011-12-14
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      • 2021-08-22
      • 1970-01-01
      • 2015-02-12
      相关资源
      最近更新 更多