过去我使用过bind1st 和bind2nd 函数来对STL 容器进行直接操作。我现在有一个 MyBase 类指针的容器,为了简单起见,如下:
class X
{
public:
std::string getName() const;
};
我想使用 for_each 调用以下静态函数并绑定第一个和第二个参数,如下所示:
StaticFuncClass::doSomething(ptr->getName() 、 funcReturningString() );
我将如何使用 for_each 并绑定该函数的两个参数?
我正在寻找类似的东西:
for_each(ctr.begin(), ctr.end(),
bind2Args(StaticFuncClass::doSomething(),
mem_fun(&X::getName),
funcReturningString());
我看到Boost提供了它自己的绑定函数,看起来像在这里有用的东西,但是STL解决方案是什么?
预先感谢您的回复。
In the past I've used the bind1st and bind2nd functions in order to do straight forward operations on STL containers. I now have a container of MyBase class pointers that are for simplicities sake the following:
class X
{
public:
std::string getName() const;
};
I want to call the following static function using for_each and binding both the 1st and 2nd parameters as such:
StaticFuncClass::doSomething(ptr->getName(), funcReturningString() );
How would I use for_each and bind both parameters of this function?
I'm looking for something along the lines of:
for_each(ctr.begin(), ctr.end(),
bind2Args(StaticFuncClass::doSomething(),
mem_fun(&X::getName),
funcReturningString());
I see Boost offers a bind function of its own that looks like something that would be of use here, but what is the STL solution?
Thanks in advance for your responses.
发布评论
评论(3)
当绑定语法变得太奇怪时,一个可靠的后备方案是定义自己的仿函数:
无论如何,这或多或少是绑定函数在幕后所做的事情。
A reliable fallback when the bind-syntax gets too weird is to define your own functor:
This is more or less what the
bind
functions do behind the scenes anyway.“STL 解决方案”是编写您自己的绑定器...这就是他们创建强大的 boost::bind 的原因。
The "STL solution" would be to write your own binder... that's why they created the powerful boost::bind.
您可以创建一个本地函子结构,该结构可以由编译器内联(如 Jalf 所示),也可以使用一个简单的函数:
You can either create a local functor structure, which can be inlined by the compiler (as Jalf showed), or use a simple function: