开发者

How to create a functor that will read next value from input stream?

Something like this :

std::bind1st(std::mem_fun(&istream::get ??), cin). This does not s开发者_StackOverflow中文版eem to work for me.

EDIT:

Use :

vector<int> vNumbers;
generate_n(back_inserter(vNumbers), iNumCount, functor);


I don't think the standard binding functions let you define nullary functions. bind1st binds to the first argument of a binary function and returns a unary function that passes its parameter as the second parameter of the bound function.

You can go outside the standard library, however, and use Boost.Bind:

boost::bind(&istream::get, &cin)


std::mem_fun takes a pointer. So do

bind(std::mem_fun(&istream::get), &cin)

where

template <typename F, typename Res, typename Arg>
struct binder
{
    binder(F const& f, Arg const& arg) : f(f), arg(arg) {}
    Res operator()() { return f(arg); }
private:
    F f; Arg arg;
};

template <typename F, typename Arg>
binder<F, typename F::result_type, Arg> bind(F const& f, Arg const& arg)
{ return binder<F, typename F::result_type, Arg>(f, arg); }

You also may want to use std::istream_iterator with a custom / stolen copy_n algorithm (which sadly is not standard):

template <typename I, typename O>
O copy_n(size_t n, I first, I last, O result)
{
    size_t k = 0;
    while (first != last && k++ < n) *result++ = *first++;
    return result;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜