[英]How to pass Callback to do Gtest in c++
我正在為下面的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。 為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: cannot convert ‘void(const Json::Value&)’ to ‘ReceiverCallBack&’ {aka ‘std::function<void(const Json::Value&)>&’}
您不能將非常量引用綁定到臨時對象。
考慮這個例子:
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);
}
您會收到完全相同的錯誤消息。 所以解決方案是沒有臨時的,以便它可以綁定到引用。
#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.