【问题标题】:How to write the correct constructor for merely function pointer?如何仅为函数指针编写正确的构造函数?
【发布时间】:2013-11-13 07:44:36
【问题描述】:

我在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 b = ptr; 并没有按照你的想法去做。
  • template &lt;typename F&gt; float_func(F&amp; f) : funobj_(new wrapper&lt;F&gt;(f)) {} 其中FFuncPtr 而不是float
  • 另外,你想解决什么问题,你写了所有这些而不是仅仅使用base
  • @kfsone:我把 F 作为 FuncPtr;我只是在学习类型擦除。

标签: c++ templates functional-programming


【解决方案1】:

您应该在float_funcwrapper 构造函数中使用const F&amp;,或者干脆使用F,因为&amp;Func 是右值,不能转换为引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多