std::function<T1(T2)>比原版有T1 (*)(T2)什么优势?
我隐约记得python允许类似的东西
def foo( x ):
....
f = foo( 5 )
Run Code Online (Sandbox Code Playgroud)
在c ++中是这样的,所以如果我有一个成员函数
class C {
void foo( int x ) { ... }
so that I can define a pointer or variable that would effectively point at foo( 5 )
Run Code Online (Sandbox Code Playgroud)
我想这样做的原因是因为我有很多听众需要订阅回调并保留被调用的信息
class C {
map<int, ptrSender> m_sender;
void subscribe() {
for (const auto& p : m_sender) {
p .second->register( Callback( this, &C::onCall ) )
}
Run Code Online (Sandbox Code Playgroud)
我的问题是onCall没有返回哪个发送回叫,但我需要这些信息.所以,而不是做这样的事情
void subscribe() {
m_sender[0]->register( Callback( this, onCall_0 ) );
m_sender[1]->register( Callback( this, onCall_1 …Run Code Online (Sandbox Code Playgroud) std::bind当我偶然发现以下答案时,我试图阅读和理解:
我看到如下的一个陈述:
auto callback = std::bind(&MyClass::afterCompleteCallback, this, std::placeholders::_1);
Run Code Online (Sandbox Code Playgroud)
我无法理解'this'指针的用法是什么,何时应该使用它?'this'指针意味着当前的对象地址本身,所以它意味着'使用这个对象' - 如果是这样的话我怎么能在类之外使用相同的语句仍具有相同的含义?
我在 SO 上找到了这个答案
我在回答中做了一切,但我收到一个错误
有我的代码
我需要传递回调的方法
/*static*/ void Utils::copy_files(std::function<void(int, int)> progress_callback,
std::string const & path_from,
std::string const & path_to)
{
....
}
Run Code Online (Sandbox Code Playgroud)
我的回调实现
void TV_DepthCamAgent::progress_callback(int count, int copied_file)
{
...
}
Run Code Online (Sandbox Code Playgroud)
用法
void TV_DepthCamAgent::foo()
{
...
auto callback = std::bind(&TV_DepthCamAgent::progress_callback,
this);
shared::Utils::copy_files(callback, path_from_copy, path_to_copy);
...
}
Run Code Online (Sandbox Code Playgroud)
我得到了一个错误
SE0312 不存在从“std::_Binder”到“std::function”的合适的用户定义转换
错误 C2664“void shared::Utils::copy_files(std::function,const std::string &,const std::string &)”:无法将参数 1 从“std::_Binder”转换为“std::function” '
我究竟做错了什么?