问题描述
我正在尝试编写一个名为Binder的模板类,该类将整个函数和参数绑定在一起,以绑定函数的返回类型来区分,这是我的方法:
I am trying to write a template class named Binder that bind functions and parameters as whole, distinguished by the returning type of the binded function, this is my approach:
template <typename return_type>
class Binder
{
public:
virtual return_type call() {}
};
调用call
将调用一些带有参数的预绑定函数,并返回结果.我想要一些从Binder继承的模板类来完成真正的绑定工作.下面是一个单参数函数绑定类:
invoking call
will invoke some pre-binded functions with parameters, and return the result.I want some template classes inherited from Binder that do the real binding job.below is a one-parameter-function binding class:
template<typename func_t, typename param0_t>
class Binder_1 : public Binder< ***return_type*** >
// HOW TO DETERMINE THE RETURN TYPE OF func_t?
// decltype(func(param0)) is available when writing call(),
// but at this point, I can't use the variables...
{
public:
const func_t &func;
const param0_t ¶m0;
Binder_1 (const func_t &func, const param0_t ¶m0)
: func(func), param0(param0) {}
decltype(func(param0)) call()
{
return func(param0);
}
}
// Binder_2, Binder_3, ....
这是我想要实现的:
template<typename func_t, typename param0_t>
Binder_1<func_t, param0_t> bind(const func_t &func, const param0_t ¶m0)
{
reurn Binder_1<func_t, param0_t>(func, param0);
}
// ... `bind` for 2, 3, 4, .... number of paramters
int func(int t) { return t; }
double foo2(double a, double b) { return a > b ? a : b; }
double foo1(double a) { return a; }
int main()
{
Binder<int> int_binder = bind(func, 1);
int result = int_binder.call(); // this actually calls func(1);
Binder<double> double_binder = bind(foo2, 1.0, 2.0);
double tmp = double_binder.call(); // calls foo2(1.0, 2.0);
double_binder = bind(foo1, 1.0);
tmp = double_binder.call(); // calls foo1(1.0)
}
boost库中的bind
函数是否可以调整以实现此功能?也欢迎类似的解决方案!
can bind
function in boost library be adapted to achieve this functionality?similar solutions are welcome too!
推荐答案
这是一个虚函数,声明为:
This is a dummy function declared as:
template <typename T>
typename std::add_rvalue_reference<T>::type declval();
// This means it returns T&& if T is no a reference
// or T& if T is already a reference
而且从未真正定义过.
因此,只能在未评估的上下文中使用它,例如sizeof
或... decltype
!
It is therefore only to be used within unevaluated contexts such as sizeof
or... decltype
!
有了这个,你得到:
template<typename func_t, typename param0_t>
class Binder_1: public Binder<decltype(std::declval<func_t>()(std::declval<param0_t>())>
这有点冗长,但是,嘿!它有效:)
It is a bit verbose, but hey! It works :)
这篇关于如何推导模板中函数的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!