c++ - g++ 4.8.2: could not convert from function pointer to std::function<> -
i'm trying write class takes, constructor parameter, factory function creates instance of same class on transformed version of input. trivial example, functor class takes int, prints it, , returns functor prints input's successor.
i'm getting errors of form
error: not convert 'foo' 'type(*)(int)' 'std::function<type(int)>'
the seems arise factory functions passed constructors.
using function pointer instead of std::function<>
works fine, hoping c++11 i'd able avoid function pointers.
here's example:
#include <functional> #include <iostream> // std::function-returning-int param in ctor default value // works fine class princ; // "print , increment" using worker = std::function<int(int)>; int foo(int i) { std::cout << << 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 default value // fails, @ 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) , 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 << << std::endl; return princ2(i+1); // error: not convert 'bar' 'princ2 (*)(int) 'factory {aka std::function<princ2(int)>' } int main() { auto p1 = princ {1}; auto p2 = princ{p1()}; p2(); auto p3 = princ2 {1}; // error: not convert 'bar' 'princ2 (*)(int) 'factory {aka std::function<princ2(int)>' auto p4 = p3(); p4(); return 0; }
what doing wrong?
edit: thelink2012's suggestion try princ2(int i, factory fn = factory(bar))
works fine on "repro" above, fails on motivating example (github link; relevant code erdos.h:35-54 around parsestep , parsefunction). drawing board better repro....
the following part of code, part appears relevant compiler error you're asking about, compiles cleanly gcc 4.9.2 using -std=c++11
mode:
#include <functional> #include <iostream> using worker = std::function<int(int)>; int foo(int i) { std::cout << << 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_; };
most bug in older gcc you're using. upgrade more recent version of gcc.
Comments
Post a Comment