关闭。这个问题需要debugging details .它目前不接受答案。
想改进这个问题?将问题更新为 on-topic对于堆栈溢出。
1年前关闭。
Improve this question
我需要对 AddToDB() API 执行单元测试。下面是我的尝试,但是当我使用下面提到的通知类型 2 创建回调时出现错误
// callback for typedef std::function<bool(std::string)> strnotify;
bool StringNotify(std::string){
std::cout<<"String success";
return true;
}
// callback for typedef std::function<void(strnotify &)> notify;
void StringObject(strnotify & obj){ // i get error here as type is not allowed
std::cout<<"string obj success";
}
//Call to API
AddToDB(StringObject)
我收到错误,因为类型是不允许的。
最佳答案
是的,您的代码运行良好,例如 Chris Dodd,但只有 AddToBase
功能。您不能为 std::function<void(strnotify &)> notify
创建函数,因为您使用了对 std::functions<Type>
的引用目的。
此代码工作正常:
using strnotify = std::function<bool(std::string)>;
using notify = std::function<void(strnotify& )>;
bool AddToDB(notify data) {
// do something...
return true;
}
int main() {
auto fun = [](strnotify& s) -> void { /*do something */};
auto fun2 = [](std::string s) -> bool {};
//fun(fun2); // now work :(
AddToDB(fun); // work!
return 0;
}
但是如果你在主函数中取消注释行,你会得到错误:gcc 10.2: 48:13: no match for call to '(main()::<lambda(strnotify&)>) (main()::<lambda(std::string)>&)'
那么,我们该如何解决呢?我有两个方法给你:
std::function<void(strnotify)> notify
; strnotify
对象并使用成函数。 godbolt 中的示例. 并使用
using
优先于 typedef
请!祝你好运!
关于c++ - std::function 不允许通过类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64346844/