【发布时间】:2015-05-12 01:28:11
【问题描述】:
我正在尝试编写一个类,该类将一个工厂函数作为构造函数参数,该工厂函数在输入的转换版本上创建同一类的另一个实例。举个简单的例子,一个仿函数类,它接受一个 int,打印它,然后返回另一个打印输入后继的仿函数。
我收到表单错误
error: could not convert 'foo' from 'Type(*)(int)' to 'std::function<Type(int)>'
似乎只有工厂函数传入构造函数。
使用函数指针而不是 std::function<> 可以正常工作,但我希望使用 C++11 能够避免使用函数指针。
这是一个例子:
#include <functional>
#include <iostream>
// std::function-returning-int param in ctor with default value
// This works fine
class PrInc; // "print and increment"
using Worker = std::function<int(int)>;
int foo(int i) {
std::cout << i << std::endl;
return i+1;
}
class PrInc {
public:
PrInc(int i, Worker fn = foo) : i_(i), fn_(fn) {}
int operator()() { return fn_(i_); }
private:
int i_;
Worker fn_;
};
// std::function-returning-PrInc2 param in ctor with default value
// This fails, at least on g++ 4.8.2 --std=c++11
class PrInc2;
using Factory = std::function<PrInc2(int)>;
// Use function ptrs (instead of std::function<>s) and it works fine
//typedef PrInc2 (*Factory)(int);
PrInc2 bar(int);
class PrInc2 {
public:
PrInc2(int i, Factory fn = bar) : i_(i), fn_(fn) {}
PrInc2 operator()() { return fn_(i_); }
private:
int i_;
Factory fn_;
};
PrInc2 bar(int i) {
std::cout << i << std::endl;
return PrInc2(i+1);
// error: could not convert 'bar' from 'PrInc2 (*)(int) to 'Factory {aka std::function<PrInc2(int)>'
}
int main() {
auto p1 = PrInc {1};
auto p2 = PrInc{p1()};
p2();
auto p3 = PrInc2 {1};
// error: could not convert 'bar' from 'PrInc2 (*)(int) to 'Factory {aka std::function<PrInc2(int)>'
auto p4 = p3();
p4();
return 0;
}
我做错了什么?
编辑: thelink2012 建议尝试PrInc2(int i, Factory fn = Factory(bar)) 在上面的“repro”上工作正常,但在motivating example 上失败(GitHub 链接;相关代码是 erdos.h:35-54 左右ParseStep 和 ParseFunction)。回到绘图板以获得更好的再现......
【问题讨论】:
-
同时,请尝试
PrInc2(int i, Factory fn = Factory(bar)),在 g++4.8.1 上使用 compiles。 -
感谢thelink2012,效果很好。