【发布时间】:2014-12-20 19:18:22
【问题描述】:
我正在组合一个“简单”的模板类。它提供了对数据库执行某些操作的接口,因此还有其他成员(主要用于对容器成员进行操作)。然而,就我们的目的而言,模板类看起来像这样:
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?换句话说,对于一些看起来像void (SomeClass*, std::back_insert_iterator<std::vector<T> >, int, bool)的任意函数签名S和看起来像void (SomeClass*, std::back_insert_iterator<std::vector<T> >, double, double, bool)的一些其他任意函数签名O我如何编写这个模板类,使得Operate的签名为@第一个为 987654332@,第二个为void (double, double, bool),并将其值传递给the_operation的第 3-N 个参数?
在我的搜索中,我找不到任何与此类似的问题。
【问题讨论】:
-
编译器应该如何检查参数类型是否与函数参数类型兼容?它应该如何插入从参数类型到函数参数类型的转换?
-
我不知道。回答这是回答问题的一部分,不是吗?预期用途是在编译时和运行时参数类型与参数类型匹配。
-
据我所知,任意类型的集合是不可能的。当您将某些内容存储在
boost::function中时,您会删除有关它的所有信息(对于外部)并用单个接口(返回值+参数类型)替换它。boost::function似乎也不支持省略号。您可以通过在boost::function的函数签名中添加类似void*的内容,然后通过此指针传递其他参数来解决该问题。但是,这既不包括类型检查也不包括转换。 -
在这种情况下,我想要的东西不能直接通过
boost::function获得。我可以尝试其他可能的实现吗? -
@caps Lemme 确保我理解正确。你有
S是一些函数,比如说,4 个参数......并且你想绑定前两个参数,并让结果是一个函数,它接受 2 个参数并调用the_operation与 2 个绑定的参数和两个通过了?
标签: c++ templates boost c++03 boost-bind