如何解决如何通过回调在C ++中执行Gtest
我正在为下面的Setter
方法编写Gtest,并且在从Gtest套件传递回调方法ClientReceiver
时遇到错误。下面是代码片段
namespace BaseClient {
class ClientTop : public JsonClient {
public:
typedef std::function<void(const Json::Value & info)> ReceiverCallBack;
public:
ClientTop(std::string name,int add);
bool Setter(const std::string & value,ReceiverCallBack & listener);
};
}
这里是Setter方法的GTest。调用ClientTop_Obj->Setter(Value,ClientReceiver)
参数的ClientReceiver
时出现错误
void ClientReceiver(const Json::Value & data){
std::cout<<"Call back received\n";
}
TEST_F(BsrfClientBaseTest,setReceiver) {
std::string value = "Run";
bool ret = ClientTop_Obj->Setter(Value,ClientReceiver);
}
收到错误
error: cannot convert ‘void(const Json::Value&)’ to ‘ReceiverCallBack&’ {aka ‘std::function<void(const Json::Value&)>&’}
解决方法
您不能将非常量引用绑定到临时目录。
考虑this example:
bool func(int & l);
bool foobar() {
// It doesn't like to bind a temporary to the non-const reference.
// error: cannot bind non-const lvalue reference of type 'callback_func&' {aka 'std::function<void(const int&)>&'} to an rvalue of type 'callback_func' {aka 'std::function<void(const int&)>'}
return func(10);
}
您得到exact same error message。因此解决方案是不要使用临时文件,以便可以绑定到引用。
#include <functional>
using callback_func = std::function<void(const int & param)>;
class example {
public:
bool setter(callback_func & l);
};
void callback(const int & i)
{
return;
}
bool foobar() {
example e;
// It doesn't like to bind a temporary to the non-const reference.
// error: cannot bind non-const lvalue reference of type 'callback_func&' {aka 'std::function<void(const int&)>&'} to an rvalue of type 'callback_func' {aka 'std::function<void(const int&)>'}
// return e.setter(callback_func{&callback});
// So,provide a non-const for it to bind to.
callback_func f{&callback};
return e.setter(f);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。