C++ bind2nd question

C++ bind2nd question

本文关键字:question bind2nd C++      更新时间:2023-10-16

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

在这个问题中,您需要实现类似于std::bind2nd的东西。为简单起见,main使用" 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;
  }

额外加分问题:你的实现很可能不工作(这是OK的!)

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

STL如何解决这个问题?

BindSecArgoperator()需要接受一个参数(显然),它应该做的是调用"绑定"函子中的operator(),传递给它(a)传入的"第一个"参数和(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()的参数和结果类型,然后使用这些从使用这些类型作为模板类型的基类继承,然后使用基类提供的类型来模板自己的operator()实现。这些是"模板元编程"的一些基本技术,它很快就会变得复杂起来。

可能有更好的实现:

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代码

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