如何在模板中推断函数的返回类型
how to deduce the return type of a function in template
我正在尝试编写一个名为 Binder 的模板类,该模板类将函数和参数绑定为一个整体,通过绑定函数的返回类型来区分,这是我的方法:
template <typename return_type>
class Binder
{
public:
virtual return_type call() {}
};
调用call
将调用一些带有参数的预绑定函数,并返回结果。我想要一些从 Binder 继承的模板类来执行真正的绑定工作。下面是一个单参数函数绑定类:
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
功能以实现此功能?类似的解决方案也欢迎!
介绍std::declval<T>()
.
这是一个虚拟函数,声明为:
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
!
有了这个,您可以获得:
template<typename func_t, typename param0_t>
class Binder_1: public Binder<decltype(std::declval<func_t>()(std::declval<param0_t>())>
这有点啰嗦,但是嘿!它适用于:)
您可以使用result_of
.
相关文章:
- 检查函数返回类型是否与STL容器类型值相同
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 在 c++ 中将函数返回类型指定为模板参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 如何避免模板函数返回类型重复?
- 从类型bankAccount的返回值到函数返回类型int没有可行的转换
- 为什么在某些情况下从函数返回类型中删除 cv 限定符?
- 模板类内模板类的函数返回类型
- 为什么函数返回类型中不允许参数推导?
- 函数返回类型之前的"define"
- C++推断要隐式调用的模板函数返回类型
- 具有不同模板参数的函数返回类型
- 当函数返回类型为父类时,如何返回子类的对象?
- C++:在原型中声明"auto"函数返回类型仍然会导致在扣除错误之前使用"auto&quo
- C++14 'auto'能够获取函数返回类型,我们还需要 std::result_of<> 吗?
- 函数返回类型中的模板类型推断
- 嵌套模板类返回类型在 C++ 中的头文件中函数返回类型的语法
- C++重写 void 函数返回类型会导致生成失败
- 从函数内部推断函数返回类型
- C++嵌套类函数返回类型和命名空间