【问题标题】:Dereferencing pointer to functor inside a dereferenced class在取消引用的类中取消引用指向函子的指针
【发布时间】:2013-12-18 10:40:00
【问题描述】:

我有一个这样的函子

struct foo
{
    int a;
    foo(a) : a(a) {}
    int operator()(int b) { return a+b; }
};

还有这样的课

class bar
{        
    public:
    foo* my_ftor;
    bar(foo* my_ftor) : my_ftor(my_ftor) {}
    ~bar() {}
};

然后假设一个指向这个类的指针,其中包含一个指向 foo 的指针。

foo MyFoo(20);
bar MyBar(&MyFoo);

在一个函数中,我传递了对 bar 的引用,并且我想运行仿函数。我的工作方式如下:

void AnyFunction(bar* RefToBar)
{
    int y;
    y = RefToBar->my_ftor->operator()(25);
}

还有其他“更简洁”的方法来取消对仿函数的引用吗?类似于

y = RefToBar->my_ftor(25);

不会工作,很遗憾......

有什么想法吗?谢谢

【问题讨论】:

  • (*RefToBar->my_ftor)(25)
  • 您还可以创建一个智能指针到函子类,它本身就是一个函子,只需调用指向对象的operator()。使用 C++11,它可以成为一个完全通用的模板。
  • bar* 不是参考

标签: c++ oop pointers functor


【解决方案1】:

使用真实的参考资料:

class bar {
public:
  foo &my_ftor;

  bar (foo &f) : my_ftor(f) {}
};


void AnyFunction (bar &reftobar) {
    int y = reftobar.my_ftor(25);
}

然后这样调用

foo myFoo(20);
bar myBar (myFoo);

AnyFunction (myBar);

为了完整起见,这是另一个更现代的答案。

class foo {
public:
    foo (int i) : a(i) {}

    int operator() (int x) const {
        return x + a;
    }
private:
    int a;
};

template <typename F>
void AnyFunction (const F &func) {
    int y = func(25);
}

所以你可以直接传入foo

AnyFunction (foo (20));

或者其他类型的函数对象,比如 lambda:

AnyFunction([](int x) -> int {
    return x + 20;
});

您还可以扩展 bar 以包含以下功能:

int run_foo (int x) const {
    return my_ftor (x);
}

并绑定它(#include &lt;functional&gt;):

AnyFunction (std::bind (&bar::run_foo, &myBar, std::placeholders::_1));

【讨论】:

  • 我猜我的 C 习惯阻止我在 C++ 中使用 &,必须深入了解它。不错。
  • 就像指针一样,在完成myBar 之前,确保myFoo 不会超出范围。
【解决方案2】:

使用std::function,它们旨在容纳任何类型的函子。

#include <functional>
#include <iostream>

struct foo
{
    int _a;
    foo(int a) : _a(a) {}
    int operator()(int b) { return _a+b; }
};


class bar
{        
public:
    std::function<int (int)> _ftor;

    bar(std::function<int (int)> my_ftor) : _ftor(my_ftor) {}
    ~bar() {}
};

void AnyFunction(bar& RefToBar)
{
    int y = RefToBar._ftor(25);
    std::cout << "Y: " << y << std::endl;
}

int AnotherFunction(int b)
{
    return b + 11;
}

int main(int argc, char const *argv[])
{
    foo MyFoo(20);
    bar MyBar(MyFoo);
    bar MyBar_2(AnotherFunction);
    bar MyBar_3([](int b) { return b + 56; });


    AnyFunction(MyBar);
    AnyFunction(MyBar_2);
    AnyFunction(MyBar_3);
    return 0;
}

http://ideone.com/K3QRRV

【讨论】:

    【解决方案3】:
    y = (*RefToBar->my_ftor)(25);
    

    (最好使用 std::function 并且不要违反 demeter)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-04
      • 2011-12-10
      • 1970-01-01
      • 2014-02-01
      • 1970-01-01
      • 2012-03-25
      相关资源
      最近更新 更多