简体   繁体   English

我用这个简单的方法调用转发类重新发明了轮子吗?

[英]Am I reinventing the wheel with this trivial method call forwarding class?

I just found myself creating a class 我发现自己创造了一堂课

template <typename T> struct invoker {
  void operator()(T& it) const {it();}
};

so I could pass an invoker<foo> to something (which isn't under my control) which wants to call invoker<foo>::operator()(foo&) on it repeatedly with different foo instances, to get it to forward those calls to the foo 's foo::operator()() method. 所以我可以将invoker<foo>传递给某些东西(不受我的控制),它想要用不同的foo实例反复invoker<foo>::operator()(foo&)它上面的调用invoker<foo>::operator()(foo&) ,以使它转发那些调用foofoo::operator()()方法。

I know it's only a few lines, but this seems like the sort of thing which is probably already provided for by STL's functional, or boost::bind somehow. 我知道它只有几行,但这似乎是STL的功能或boost::bind以某种方式提供的东西。 Except I can't see the trick, if there is one. 除非我看不到诀窍,如果有的话。 (I'm sure I'm not the first person to use something very like this; does it have a name ?) (我敢肯定我不是第一个使用这种东西的人;它有名字吗?)

Well, you can use std::bind , probably boost::bind as well to achieve the same behaviour: 好吧,你可以使用std::bind ,也可以使用boost::bind来实现相同的行为:

#include <string>
#include <iostream>
#include <functional>

struct foo {
    void operator()() {
        std::cout << "Hallo, im at addr: " << std::hex << this << std::endl;
    }
};

int main() {
    std::function<void(foo*)> fun = std::bind(&foo::operator(), std::placeholders::_1);
    foo f1, f2;
    fun(&f1);
    fun(&f2);
}

Outputs: 输出:

Hallo, im at addr: 0xbffc396a
Hallo, im at addr: 0xbffc3969

If you use a template class for the argument type, you can have the same behvaiour without reinventing the wheel. 如果您为参数类型使用模板类,则可以在不重新发明轮子的情况下使用相同的behvaiour。

Edit : as Crazy Eddie pointed out, you can just use boost::mem_fn or std::mem_fn : 编辑 :正如Crazy Eddie指出的那样,你可以使用boost::mem_fnstd::mem_fn

std::function<void(foo*)> fun = std::mem_fn(&foo::operator());

Instead of bind . 而不是bind

Yeah, you're reinventing the wheel. 是的,你正在重新发明轮子。 std::mem_fun_ref does what you want. std :: mem_fun_ref做你想要的。

std::vector<foo> foos;

...

std::for_each(foos.begin(), foos.end(), std::mem_fun_ref(&foo::operator()));

Alternatively: 或者:

std::vector<foo*> foos;

...

std::for_each(foos.begin(), foos.end(), std::mem_fun(&foo::operator()));

Not having to mess with whether your param is ptr or not is one great benefit of boost::mem_fn. 不必弄乱你的param是否是ptr是boost :: mem_fn的一大好处。

Anything much more complex than that though and you begin running into trouble with the C++03 binders and need something more expressive like boost.bind. 任何比这更复杂的东西,你开始遇到C ++ 03绑定器的麻烦,需要像boost.bind更具表现力的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM