我用这个简单的方法调用转发类重新发明轮子? [英] 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();}
};
,所以我可以传递 invoker< foo>
到不同的<$ c>重复调用 invoker< foo> :: operator()(foo&)
$ c> foo 的实例,让它转发这些调用到 foo
的 foo :: operator ()
方法。
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.
我知道它只有几行,但这似乎是类似的东西,可能已经提供了STL功能,或 boost :: bind
不知何故。除非我看不到把戏,如果有一个。 (我相信我不是第一个使用这样的东西的人,它有一个名字吗?)
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. 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 ?)
推荐答案
是的,你是重塑的轮子。 std :: mem_fun_ref做你想要的。
Yeah, you're reinventing the wheel. std::mem_fun_ref does what you want.
std::vector<foo> foos;
...
std::for_each(foos.begin(), foos.end(), std::mem_fun_ref(&foo::operator()));
或者:
std::vector<foo*> foos;
...
std::for_each(foos.begin(), foos.end(), std::mem_fun(&foo::operator()));
不用担心你的参数是ptr还是不是boost :: mem_fn 。
Not having to mess with whether your param is ptr or not is one great benefit of boost::mem_fn.
任何比这更复杂的事情,你开始遇到C ++ 03 binder的麻烦,需要一些更具表现力的东西,如boost.bind。
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.
这篇关于我用这个简单的方法调用转发类重新发明轮子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!