我需要使用另一个类的unique_ptr实现回调方法:
#include <iostream>
#include <functional>
#include <memory>
class A
{
public:
void Show(void) {}
};
class B
{
public:
void SetCB(std::function<void(void)> callb);
private:
std::function<void(void)> cb;
};
void B::SetCB(std::function<void(void)> callb)
{
cb= callb;
}
int main()
{
std::unique_ptr<A> a1 = std::make_unique<A>();
std::unique_ptr<B> b1 = std::make_unique<B>();
b1->SetCB(&a1->Show, a1.get());
}
我收到编译错误:
$ c++ -std=c++14 try68.cpp
try68.cpp: In function 'int main()':
try68.cpp:28:29: error: no matching function for call to 'B::SetCB(<unresolved overloaded function type>, std::unique_ptr<A>::pointer)'
b1->SetCB(a1->Show, a1.get());
^
try68.cpp:28:29: note: candidate is:
try68.cpp:19:6: note: void B::SetCB(std::function<void()>)
void B::SetCB(std::function<void(void)> callb)
^
try68.cpp:19:6: note: candidate expects 1 argument, 2 provided
^
是否无法使用unique_ptr设置回调方法?
答案 0 :(得分:1)
使用lambda,它会像魅力一样工作:
b1->SetCB([&](){a1->Show();});
您可能还想move
进行回调:
void B::SetCB(std::function<void(void)> callb)
{
cb = std::move(callb);
}