c++ - 将函数绑定(bind)到范围以生成迭代函数

标签 c++ templates boost foreach boost-bind

我正在尝试实现自己的 bind_range可以绑定(bind)一个范围。它应该允许这样的客户端代码:

void f(int x, int y)
{
    std::cout << x + y << ',';
}

std::vector<int> v1; // contains 1,2,3

void go()
{
    boost::function<void(int y)> f_bound = bind_range(f, v1, _1);
    f_bound(10); // prints 11,12,13,
}

在上面的代码中,我的模板 bind_range检测到 v1符合 ForwardRangeConcept<>并且它的值类型与 f() 兼容的第一个参数。然后它生成一个函数对象,该对象将遍历 v1。 , 调用 f()对于每个值。

我知道上面的内容可以通过在调用代码中使用某种形式的 for-each 结构来实现,但我想获取绑定(bind)函数并在以后使用它。

以上就是我想要实现的本质。我已经阅读了 C++ Template Metaprogramming 的拷贝并查看了 boost::bind实现,但我无法开始解决方案。我也有一种挥之不去的感觉,像这样的东西已经存在于 Boost 库的某处。

扩展:

绑定(bind)多个范围。例如:

std::vector<int> v10; // contains 10,20,30

void go_multiple()
{
    boost::function<void()> f_bound = bind_range(f, v10, v1);
    f_bound(); // prints 11,12,13,21,22,23,31,32,33,
}

处理返回类型。我不需要迭代调用的返回类型,但可以想象有人可能想要存储或处理每个返回值。我确信这可以通过某种 Lamda 类型的构造巧妙地完成。

最佳答案

据我所知,这在 Boost 中不存在,因为它很容易用 for_eachbind 重现,例如:

function<void()> bound = bind(
    for_each<vector<int>::iterator, function<void(int)> >, 
    v1.begin(), v1.end(), func
);`

这很简单。您只需要创建一个模板化的仿函数 bind_range ,其中包含一个构造函数,该构造函数获取绑定(bind)信息(即容器和仿函数)和一个将函数应用于容器的 operator() .

但是请注意,像这样保存仿函数供以后使用通常很危险,因为 bind_range 对象最终可能会引用一个不再存在的容器。

一个简单的例子:

template<typename Container, typename Function>
struct bind_range {
    bind_range(Container& target, Function func) 
        : container(target), function(func) { }

    void operator()() {
        std::for_each(container.begin(), container.end(), function);
    }

    Function function;
    Container& container;
};

关于c++ - 将函数绑定(bind)到范围以生成迭代函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5497605/

相关文章:

c++ - 读取 svm 数据并用更多数据重新训练?

c++ - 无法从静态方法调用指向成员函数的指针

c++ - 如何在 C++ 中实现 "virtual template function"

C++,作为模板参数传递的成员函数

c++ - boost 线程,测试线程是否准备好加入

没有 RTTI 的 C++ 双重分派(dispatch) "extensible"

c++ - C++ 中的整数除法没有按预期工作

c++ - 模板消歧器

c++ - goroutines 和 boost.fiber 之间的区别

c++ - 如何桥接 Python 和 C++