我正在组合一个“简单”的模板类。它提供了一个用于对数据库执行某些操作的接口(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
}
我的问题有两个方面。
- 我应该把什么作为
Operate
的模板参数? .即用什么代替???
- 我怎么知道
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/