使用带有 boost 绑定的 boost 函数与地图
Using boost function with boost bind with a map
在此代码中,行 (iter->second)();
调用函数 reset(new childClass())
。这个对吗 ?
如果是这种情况,它是在哪个对象上调用的?
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;
}
the line (iter->second)();
calls the function reset(new childClass())
. Is this correct?
不,它调用 reset()
。如果你想让它被称为 reset(new childClass())
,你需要将 new childClass()
作为参数传递给 boost::bind
,比如
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
时计算的,而不是调用函子时计算的。
或者你可以加一个占位符,在调用仿函数的时候传new childClass()
it is called on which object ?
它是在从传递给 boost::bind
的参数复制的对象上调用的,即 boost::shared_ptr<BaseClass>(new childClass() )
.
在此代码中,行 (iter->second)();
调用函数 reset(new childClass())
。这个对吗 ?
如果是这种情况,它是在哪个对象上调用的?
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;
}
the
line (iter->second)();
calls the functionreset(new childClass())
. Is this correct?
不,它调用 reset()
。如果你想让它被称为 reset(new childClass())
,你需要将 new childClass()
作为参数传递给 boost::bind
,比如
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
时计算的,而不是调用函子时计算的。
或者你可以加一个占位符,在调用仿函数的时候传new childClass()
it is called on which object ?
它是在从传递给 boost::bind
的参数复制的对象上调用的,即 boost::shared_ptr<BaseClass>(new childClass() )
.