What am I doing wrong with my bind function here?
I wrote my bind
function which returns a nullary functor because I don't have boost. Though this code compiles fine, it does not behave as I expected. When I input 2 as the number of numbers and try to enter them, the program terminates the first time I hit return. And, when I debug, it segfaults inside mem_fun_t::operator()
. What am I doing wrong here? And how to rectify it?
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <iterator>
#include <functional>
using namespace std;
namespace MT
{
t开发者_开发技巧emplate<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;
}
istream::get is not the right method to use, as it reads characters, not ints. You'd need to use operator>> (and selecting the right overload is very verbose), or just write a different functor:
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));
精彩评论