如何在模板中推断函数的返回类型

how to deduce the return type of a function in template

本文关键字:函数 返回类型      更新时间:2023-10-16

我正在尝试编写一个名为 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 &param0;
        Binder_1 (const func_t &func, const param0_t &param0)
            : 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 &param0)
{
    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 .