如何仅为函数指针编写正确的构造函数

How to write the correct constructor for merely function pointer?

本文关键字:构造函数 何仅 函数 指针      更新时间:2023-10-16

我按照 c++ 模板元编程编写了一个简单的 float(float) 函数对象:

class float_func
{
    struct base {
        virtual float operator()(float a) = 0;
    };
    template <typename F>
        class wrapper : public base {
            public:
                wrapper(F& f) : f_(f) { }
                virtual float operator()(float a) {
                    return f_(a);
                }
            private:
                F f_;
        };
    public:
    template <typename F> float_func(F& f) : funobj_(new wrapper<F>(f)) {}
    float operator()(float a) {
        return (*funobj_)(a);
    };
    private:
    base* funobj_;
};

我想像这样使用它:

#include <iostream>
#include <functional>
#include "my_float_fun.h"
struct FunObject {
    float operator()(float a) const {
        return a + 1;
    }
};
float Func(float a) 
{
    return a - 1;
};
typedef float (*FuncPtr)(float a);
int main()
{
    FunObject obj;
    FuncPtr ptr = &Func;
    float_func a = obj;
    float_func b = ptr;
//  float_func c = &Func; not compile
    std::function<float(float)> d = &Func;
    std::cout << a(1)  << b(2) << std::endl;
    return 0;
}

但是注释掉的行无法编译。另一方面,std::function运行良好。

我应该如何修改我的float_fun类以仅支持函数指针本身(&Func)而不是函数指针对象(ptr)?

你应该

float_func中使用const F&,或者简单地F wrapper构造函数,因为&Func是右值,不能转换为引用。