c++ - 使用 boost::bind 但允许传递任何附加参数

标签 c++ templates boost c++03 boost-bind

我正在组合一个“简单”的模板类。它提供了一个用于对数据库执行某些操作的接口(interface),因此还有其他成员(主要用于对容器成员进行操作)。然而,为了我们的目的,模板类看起来像这样:

template<typename T, //the type of objects the class will be manipulating
         typename S> //the signature of the function the class will be using
FunctionHandler
{
private:
    std::vector<T> container;
    boost::function<S> the_operation;
    SomeClass* pSC; //a database connection; implementation unimportant

    //some other members--not relevant here
public:
    boost::function<???> Operate;
    FunctionHandler(boost::function<S> the_operation_)
        : the_operation(the_operation_)
    {
        Operate = boost::bind(the_operation, pSC, std::back_inserter<std::vector<T> >,
                              /*infer that all other parameters passed to Operate
                                should be passed through to the_operation*/);
    }

    //other peripheral functions
}

我的问题有两个方面。

  1. 我应该把什么作为 Operate 的模板参数? .即用什么代替 ???
  2. 我怎么知道 boost::bind它应该传递给 Operate 的任何其他参数到 the_operation ?换句话说,对于一些任意函数签名 S看起来像 void (SomeClass*, std::back_insert_iterator<std::vector<T> >, int, bool)和其他一些任意函数签名 O看起来像 void (SomeClass*, std::back_insert_iterator<std::vector<T> >, double, double, bool)我如何编写此模板类使得 Operate签名为 void (int, bool)对于第一个和void (double, double, bool)第二个,并将其值传递给 the_operation的第 3-N 个参数?

在我的搜索中,我找不到任何与此类似的问题。

最佳答案

为什么还要使用 bind?没有它我们也能得到同样的效果。我使用 Iter 作为模板,但您可以填写正确的类型:

template <typename S, typename Iter>
class Operator
{
    boost::function<S> func_;
    SomeClass* cls_;
    Iter iter_;

public:
    Operator(function<S> func, SomeClass* cls, Iter iter)
    : func_(func), cls_(cls), iter_(iter)
    { }

    // one for each # of args
    typename boost::result_of<
        boost::function<S>(SomeClass*, Iter)
    >::type operator()() const {
        return func_(cls_, iter_);
    }

    template <typename A>
    typename boost::result_of<
        boost::function<S>(SomeClass*, Iter, A)
    >::type operator()(A a) const {
        return func_(cls_, iter_, a);
    }

    template <typename A, typename B>
    typename boost::result_of<
        boost::function<S>(SomeClass*, Iter, A, B)
    >::type operator()(A a, B b) const {
        return func_(cls_, iter_, a, b);
    }

    // etc.
};

我们正在制作所有的 operator(),但它们只有在被调用时才会被实例化 - 所以只要你调用正确的(对于任何解决方案,你无论如何都必须),这有效。

关于c++ - 使用 boost::bind 但允许传递任何附加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27583486/

相关文章:

c++ - 为什么 C 和 C++ 允许表达式 (int) + 4*5?

c++ - 什么 STL 容器执行删除之间的元素?

c++ - boost 几何: assertion_failed error C++

python - Boost::Python 和带变量的函数

c++ - dynamic_cast 由 lt_dlopen(libtool) 加载的共享库中的接口(interface)不起作用

c++ - OpenCV 中的 vector 比较 (C++)

c++ - 如何使用模板方法(c++)模拟类中的多态性?

c++ - 通过模板定义 main()

c++ - 模板特化是扩展还是覆盖通用模板?

c++ - boost::fibonacci_heap 复制构造函数损坏源堆