【问题标题】:C++ bind2nd questionC++ bind2nd 问题
【发布时间】:2011-07-23 10:22:58
【问题描述】:

这是我期末考试中出现的问题之一。我不知道我应该做什么。 我知道 BindSecArg 需要一个 () 运算符,但不确定里面是什么。

在这个问题中,您需要实现类似于 std::bind2nd 的东西。为简单起见主要 使用“for”循环编写,但可以使用“for each”和 STL 容器重写。

class Functor1 {
  public:
     int operator()(const int & i, const int & j) const {
      return i+j;
     }
};

class Functor2 {
   public:
    int operator()(const int & i, const int & j) const {
       return i*j;
     }
};

template <typename T>
class BindSecArg

};

int main () {
  Functor1 f1;
  for (int i=0; i<10; ++i) std::cout << f1(i,i) << " "; //0 2 4 6 8 10
  std::cout << std::endl;

  Functor2 f2;
  for (int i=0; i<10; ++i) std::cout << f2(i,i) << " "; //0 1 4 9 16 25
  std::cout << std::endl;

  BindSecArg<Functor1> b1(4); //bind second argument of Functor1 to 4
  for (int i=0; i<10; ++i) std::cout << b1(i) << " "; //4 5 6 7 8 9
  std::cout << std::endl;

  BindSecArg<Functor2> b2(4); //bind second argument of Functor2 to 4
  for (int i=0; i<10; ++i) std::cout << b2(i) << " "; //0 4 8 12 16 20
  std::cout << std::endl;
  }

额外的问题:你的实现很可能不起作用(这没关系!)

 class Functor3 {
    public:
      std::string operator()(const std::string & i, const std::string & j) const {
        return i+j;
      }
 };

STL 如何解决这个问题?

【问题讨论】:

标签: c++ stl bind2nd


【解决方案1】:

BindSecArgoperator() 需要一个参数(显然),它应该做的是从“绑定”函子中调用 operator(),并传递它(a)传入的“first " 参数和 (b) “绑定”的第二个参数。

所以我们需要构造一个绑定函子类的实例(以便我们可以进行调用),并且我们需要记住第二个参数。我们将通过数据成员处理这两个问题。

看起来像:

template <typename T>
class BindSecArg
    T toCall;
    int second;
    public:
    // To initialize, we default-construct the bound-functor-instance, and copy the
    // constructor parameter for our bound-parameter.
    BindSecArg(int second): toCall(), second(second) {}
    // To call, see the above discussion.
    int operator() (int first) { return toCall(first, second); }
};

标准库(请不要说“STL”)bind2nd 通过期望 T 是“AdaptableBinaryFunction”来解决这个问题,即提供一些typedef 成员来标识operator() 的参数和结果类型,然后使用这些从使用这些 typedef 作为模板类型的基类继承,然后使用基类提供的 typedef 模板化它自己的 operator() 实现。这些是“模板元编程”的一些基本技术,而且很快就会变得复杂。您应该为此查找一些单独的阅读资源。

【讨论】:

  • 感谢 Karl 的详尽解释。
【解决方案2】:

可能有更好的实现:

template <typename T>
class BindSecArg
{
public:
   BindSecArg(int value2) : m_value2(value2){ };
   int operator()(int value1) { return T()(value1, m_value2);}
private:
   int m_value2;
};

在我对您问题的评论中发布的链接中,您可以找到 stl 代码。

【讨论】:

  • 它更像是丢失而不是错误。期末考试是写的,所以它更加混乱。构造函数我实现了,和wiso的构造函数一样,但是不能实现operator()。
【解决方案3】:

Inside 调用 Functor.operator(),在其构造函数中传递给 BindSecArg 的值作为第二个参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多