如何创建一个将从输入流读取下一个值的函子?

发布于 2024-10-01 23:49:23 字数 236 浏览 0 评论 0原文

像这样的东西:

std::bind1st(std::mem_fun(&istream::get ??), cin)。这似乎对我不起作用。

编辑:

使用:

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

Something like this :

std::bind1st(std::mem_fun(&istream::get ??), cin). This does not seem to work for me.

EDIT:

Use :

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

指尖上的星空 2024-10-08 23:49:23

我认为标准绑定函数不允许您定义无效函数。 bind1st 绑定到二元函数的第一个参数,并返回一个一元函数,该函数将其参数作为绑定函数的第二个参数传递。

但是,您可以超出标准库并使用 Boost.Bind:

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

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)
两仪 2024-10-08 23:49:23

std::mem_fun 接受一个指针。因此

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

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

您可能还想将 std::istream_iterator 与自定义/窃取的 copy_n 算法一起使用(遗憾的是这不是标准的):

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

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文