首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ bind2nd问题

C++ bind2nd问题
EN

Stack Overflow用户
提问于 2011-07-23 18:22:59
回答 3查看 548关注 0票数 1

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

在这个问题中,你需要实现一些类似于std::bind2nd的东西。为简单起见,main是使用“For”-loop编写的,但它可以用“for each”和STL容器重写。

代码语言:javascript
复制
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;
  }

额外的学分问题:你的实现很可能不能工作(这没问题!)使用

代码语言:javascript
复制
 class Functor3 {
    public:
      std::string operator()(const std::string & i, const std::string & j) const {
        return i+j;
      }
 };

STL是如何解决这个问题的?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-07-23 18:39:54

也许有更好的实现:

代码语言:javascript
复制
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代码。

票数 2
EN

Stack Overflow用户

发布于 2011-07-23 18:47:06

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

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

这看起来像是:

代码语言:javascript
复制
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“来解决这个问题,即提供一些标识operator()的参数和结果类型的typedef成员,然后使用这些成员来继承基类(使用这些typedefs作为模板类型),然后使用基类提供的typedefs来为自己的operator()实现提供模板。这些是“模板元编程”的一些基本技术,而且它很快就变得复杂起来。为此,您应该查找一些单独的阅读资源。

票数 3
EN

Stack Overflow用户

发布于 2011-07-23 18:37:29

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6799755

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档