如何仅为函数指针编写正确的构造函数
How to write the correct constructor for merely function pointer?
我按照 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
是右值,不能转换为引用。
相关文章:
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- 将向量从 N1 缩小到 N2 项,而不触发默认构造函数并仅使用 move 语义
- 仅当构造函数具有参数时,C++ 公共成员才能访问
- 复制构造函数是始终隐式定义,还是仅在使用时定义?
- 如何实现构造函数,使其仅接受使用 typeid 的输入迭代器?
- 当(且仅当)对象具有复制构造函数时,如何复制对象?
- 如何仅从类类型推断类构造函数参数的类型
- C 如何仅实现多个继承类的一个构造函数
- 包含仅移动类型的类的构造函数应通过引用还是通过右值引用接收仅移动类型?
- 为什么"S x({})"仅在GCC 7/C++1z模式下调用默认构造函数?
- 仅当基础类型具有模板类型构造函数时,才实现这些构造函数
- 如何仅在给定n个以上参数的情况下启用可变模板构造函数_if
- 如何将一个类的构造函数的调用限制为仅其工厂类
- 仅继承父构造函数的某些参数
- 为什么在unordered_map emplace中使用矢量构造函数仅占参数的最后值
- 双重列表复制构造函数:与单一列表复制构造函数有何不同
- 在成员容器中复制具有仅可移动但可克隆类型的构造函数
- 仅在C++中声明默认构造函数
- postblit构造函数是否仅因源而与复制构造函数不同