[英]How to pass Callback to do Gtest in c++
I am writing Gtest for the Below Setter
method and i am getting error while passing a callback method ClientReceiver
from Gtest suite.我正在为下面的Setter
方法编写 Gtest,并且在从 Gtest 套件传递回调方法ClientReceiver
时出现错误。 Below is the code snippet下面是代码片段
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);
};
}
Here is GTest for the Setter Method.这是 Setter 方法的 GTest。 I am getting error while calling ClientTop_Obj->Setter(Value,ClientReceiver)
for ClientReceiver
parameters为ClientReceiver
参数调用ClientTop_Obj->Setter(Value,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 Received收到错误
error: cannot convert ‘void(const Json::Value&)’ to ‘ReceiverCallBack&’ {aka ‘std::function<void(const Json::Value&)>&’}
You can't bind a non-const reference to a temporary.您不能将非常量引用绑定到临时对象。
Consider 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);
}
You get the exact same error message .您会收到完全相同的错误消息。 So the solution is to not have a temporary so that it can bind to the reference.所以解决方案是没有临时的,以便它可以绑定到引用。
#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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.