[英]g++ 4.8.2: could not convert from function pointer to std::function<>
我正在嘗試編寫一個類,該類將構造函數作為工廠函數,該函數在輸入的轉換版本上創建同一類的另一個實例。 對於一個簡單的示例,仿函數類接受一個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”上運行良好,但是在激勵示例 (GitHub鏈接)上失敗了;相關代碼是erdos.h:35-54,位於ParseStep周圍和ParseFunction)。 返回繪圖板以獲得更好的再現。
代碼的以下部分(這似乎是與您要詢問的編譯器錯誤有關的唯一部分)使用-std=c++11
模式在gcc 4.9.2中進行了干凈地編譯:
#include <functional>
#include <iostream>
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_;
};
最有可能是您使用的舊版gcc中的錯誤。 升級到最新版本的gcc。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.