【问题标题】:What am I doing wrong with my bind function here?我在这里的绑定功能做错了什么?
【发布时间】:2011-05-08 13:38:00
【问题描述】:

我写了我的 bind 函数,它返回一个空函子,因为我没有 boost。虽然这段代码编译得很好,但它并没有像我预期的那样运行。当我输入 2 作为数字的数量并尝试输入它们时,程序在我第一次点击返回时终止。而且,当我调试时,它会在mem_fun_t::operator() 内出现段错误。我在这里做错了什么?又该如何整改?

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <iterator>
#include <functional>

using namespace std;

namespace MT
{
    template<class Operation>
    struct binder
    {
        protected:
            Operation _op;
            typename Operation::argument_type _arg;

        public:
            binder(Operation& fn, typename Operation::argument_type arg)
                :_op(fn), _arg(arg)
            {
            }

            typename Operation::result_type operator()()
            {
                return _op(_arg);
            }
    };

    template<class Operation, class Arg>
    binder<Operation> bind(Operation op, Arg arg)
    {
        return binder<Operation>(op, arg);
    }
};

int main()
{
    vector<int> vNumbers;
    vector<char> vOperators;
    int iNumCount = 0;
    int iNumOperators = 0;

    cout << "Enter number of number(s) :) :\n";
    cin >> iNumCount;

    int iNumber;
    cout << "Enter the " << iNumCount << " number(s):\n";

    generate_n(back_inserter(vNumbers), iNumCount, MT::bind(mem_fun(&istream::get), &cin));

    system("clear");

    copy(vNumbers.begin(), vNumbers.end(), ostream_iterator<int>(cout, " "));
    cout << endl;
}

【问题讨论】:

  • 请注意:system("clear") 不是 Windows 上的有效命令。
  • 为什么不使用来自 StdLib 的 bind1stbind2nd
  • 这似乎也是对一个非常简单的问题的疯狂混淆。
  • @DeadMG:你为什么要使用 Windows?

标签: c++ stl functional-programming


【解决方案1】:

istream::get 不是正确使用的方法,因为它读取字符,而不是整数。您需要使用 operator>> (并且选择正确的重载非常冗长),或者只是编写一个不同的仿函数:

template<class T>
struct Extract {
  istream &stream;
  Extract(istream &stream) : stream (stream) {}

  T operator()() {
    T x;
    if (!(stream >> x)) {
      // handle failure as required, possibly throw an exception
    }
    return x;
  }
};

// ...
generate_n(back_inserter(vNumbers), iNumCount, Extract<int>(cin));

【讨论】:

  • @Roger Pate:谢谢。也欢迎函子上的任何 cmets。而且,为什么 STL 中没有这样的函子?
  • copy_n()(或transform_n)与istream_iterator。 (不需要Extract&lt;&gt;,但是你需要写copy_n())。
  • @wilhelmtell:我想过,但这里更简单。
  • @nakiya:因为标准库只包括特定图书馆的厨房水槽。 :) 实际上,STL 是 1995 年左右发布的专有库,当时处理编译器支持。它被合并到 '98 标准中(进行了一些修改),但从那时起 stdlib 基本上没有改变(直到 0x,Real Soon Now™)。这是 boost 存在的一般原因,但你不能使用它。
  • 去吧 Lambda 函数队长解决这个问题。
猜你喜欢
  • 2017-09-29
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 2013-06-28
  • 2023-01-19
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
相关资源
最近更新 更多