【问题标题】:How to convert a function that returns a int to a function that returns a bool using boost::bind?如何使用 boost::bind 将返回 int 的函数转换为返回 bool 的函数?
【发布时间】:2012-12-11 22:50:36
【问题描述】:

我有类似以下内容:

 struct A{
  virtual int derp(){ 
      if(herp()) return 1; 
      else return 0; 
   }
  void slurp(){
    boost::function<bool(int x, int y)> purp = /** boost bind derp to match lvalue sig  **/;
  }
 }

有什么想法吗?我想创建基本上调用derp并忽略传入的(x,y)的函数prup。

我需要类似的东西

bool purp(int x, int y){ return derp(); }

但想避免将其创建为成员函数,而是尽可能在本地创建它?

【问题讨论】:

    标签: c++ boost boost-bind


    【解决方案1】:

    如果 C++11 可用,请考虑使用 lambda。否则,您可以使用 Boost.Lambda:

    boost::function<bool(int x, int y)> purp = !!boost::lambda::bind(&A::derp, this);
    

    这使用intbool 的标准转换。

    如果您希望A::derp 的特定返回值为true,则使用==。例如,假设您希望返回值 3 为 true

    boost::function<bool(int x, int y)> purp = boost::lambda::bind(&A::derp, this) == 3;
    

    编辑:完整示例:

    #include <iostream>
    
    #include <boost/function.hpp>
    #include <boost/lambda/lambda.hpp>
    #include <boost/lambda/bind.hpp>
    
    struct A {
        virtual int derp() {
            std::cout << "within A::derp()\n";
            return 0;
        }
        void slurp() {
            boost::function<bool(int x, int y)> purp = !!boost::lambda::bind(&A::derp, this);
            std::cout << (purp(3, 14) ? "true" : "false") << '\n';
        }
    };
    
    int main()
    {
        A a;
        a.slurp();
    }
    

    输出:

    在 A::derp() 内 错误的

    【讨论】:

      【解决方案2】:
      boost::function<bool(int x, int y)> purp = boost::bind(&A::derp, this);
      

      只要derp 返回值可以隐式转换为bool,这应该可以工作。不过,你会在 VC++ 中得到这个恼人的警告:"warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)"

      【讨论】:

        【解决方案3】:

        我不太确定 boost::bind 库以及如何处理您的情况,但如果您有启用 C++ 的环境,您可以使用 lambda 代替绑定:

        auto purp = [=](int,int) -> bool { return derp(); };
        // alternatively:
        //std::function<bool(int,int)> purp = [](int,int)->bool{return derp();};
        

        有了 lambda 支持后,突然绑定似乎不是一个很好的工具 :)

        【讨论】:

        • 你需要捕获this:[=](int, int) -&gt; bool { return derp(); };
        • @DanielTrebbien:正确,我没有注意其余的代码,错过了 derp 是成员函数而不是免费函数。
        【解决方案4】:

        布尔真/假在 C 实现中只是一个整数,你当然可以写一些东西来做到这一点。我不明白这样做的意义或为什么函数包含在结构中。主要问题是为什么您希望函数接受参数以便可以忽略它们?为什么不让函数返回 bool 而不是 int ?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-05-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-10
          • 2023-02-10
          • 1970-01-01
          相关资源
          最近更新 更多