我的绑定功能在这里做错了什么?

时间:2010-11-11 16:00:43

标签: c++ stl functional-programming

我写了bind函数,它返回一个无效的函子,因为我没有提升。尽管此代码编译良好,但它的行为并不像我预期的那样。当我输入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;
}

1 个答案:

答案 0 :(得分:0)

istream :: get不是正确的使用方法,因为它读取字符,而不是整数。您需要使用运算符&gt;&gt; (并选择正确的重载非常详细),或者只写一个不同的仿函数:

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));