gpt4 book ai didi

c++ - 使用带有 boost 绑定(bind)的 boost 函数与 map

转载 作者:行者123 更新时间:2023-11-30 03:15:15 33 4
gpt4 key购买 nike

在此代码中,行 (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() ) .

关于c++ - 使用带有 boost 绑定(bind)的 boost 函数与 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57217660/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com