c++ - std::function 不允许通过类型

标签 c++ c++11 testing

关闭。这个问题需要debugging details .它目前不接受答案。












想改进这个问题?将问题更新为 on-topic对于堆栈溢出。

1年前关闭。




Improve this question




我需要对 AddToDB() API 执行单元测试。下面是我的尝试,但是当我使用下面提到的通知类型 2 创建回调时出现错误

  • typedef std::function strnotify;
  • typedef std::function 通知;
  • bool AddToDB(通知数据);
  • // 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/

    相关文章:

    c++11 - 省略号可以/应该/将适用于元组吗?

    java - 如何指定没有输入的测试用例

    c++ - 为什么 std::weak_ptr 没有 operator->?

    c++ - 为什么我的模板化函数需要从一个迭代器到另一个迭代器的转换?

    c++ - 如何存储/检索成员函数指针以用作模板参数?

    android - 单元测试和 Android DownloadManager

    java - greenmail 服务器收不到邮件

    C++ 模板用法

    c++ - 使用 "ldaps"绑定(bind)到 ldap 服务器

    c++ - 为 OpenGL 编写我自己的三角形光栅化程序?