将boost功能与带有地图的boost bind一起使用 [英] Using boost function with boost bind with a map
问题描述
在此代码中,行(iter->second)();
调用函数reset(new childClass())
.这样对吗 ?
如果是这样,它将在哪个对象上调用?
In this code, the line (iter->second)();
calls the function reset(new childClass())
. Is this correct ?
If this is the case, it is called on which object ?
class BaseClass{
public:
virtual void foo() { std::cout << "base" << std::endl;}
};
class childClass : public BaseClass {
public:
virtual void foo() { std::cout << "derived" << std::endl;}
~childClass () {
std::cout << "childClass destructor" << std::endl;
}
};
int main()
{
typedef std::map<std::string, boost::function<void()>> Map_t;
Map_t g_cmdMap = map_list_of( "cmd",
boost::bind( static_cast<void( boost::shared_ptr<BaseClass>::* )()>( &boost::shared_ptr<BaseClass>::reset ),
boost::shared_ptr<BaseClass>(new childClass() ) )) ;
std::map<std::string, boost::function<void()>>::iterator iter;
iter = g_cmdMap.find( "cmd" );
(iter->second)();
return 0;
}
推荐答案
line (iter->second)();
调用函数reset(new childClass())
.这是正确的吗?
the
line (iter->second)();
calls the functionreset(new childClass())
. Is this correct?
否,它将调用reset()
.如果希望将其称为reset(new childClass())
,则需要将new childClass()
作为参数传递给boost::bind
No, it invokes reset()
. If you want it to be called as reset(new childClass())
, you need to pass new childClass()
to boost::bind
as argument like
boost::bind( static_cast<void( boost::shared_ptr<BaseClass>::* )(BaseClass*)>(
&boost::shared_ptr<BaseClass>::reset ),
boost::shared_ptr<BaseClass>(new childClass() ),
new childClass() )
请注意,new childClass()
本身是在调用boost::bind
时求值的,而不是在调用函子时求值的.
Note that new childClass()
itself is evaluated when boost::bind
is invoked, not the functor is invoked.
或者您可以添加一个占位符,并在调用函子时传递new childClass()
.
Or you can add a placeholder, and pass new childClass()
when call the functor.
它在哪个对象上被调用?
it is called on which object ?
调用从传递给boost::bind
的参数(即boost::shared_ptr<BaseClass>(new childClass() )
)复制的对象.
It's called on the object copied from the argument passed to boost::bind
, i.e. boost::shared_ptr<BaseClass>(new childClass() )
.
这篇关于将boost功能与带有地图的boost bind一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!