C++ typedef function definition as a class member to use later for function pointer? -
i need have class stores function definition/prototype class member in order use later function pointers based on definition.
#include <cstdlib> #include <cstdio> #include <functional> template<typename... ts> class function; template <typename r> class function<r> { public: using functype = r (*) (); function() { printf("r()\n"); } }; template <typename r, typename... a> class function<r, a...> { public: using functype = r (*) (a...); function() { printf("r(a)\n"); } }; void fn1(int i) { printf("called fn1: %d\n", i); } void fn2(int i, float f) { printf("called fn2: %d, %f\n", i, f); } void fn3() { printf("called fn3: n/a \n"); } int main(int argc, char **argv) { function<void, int> myfuncx; function<void, int, float> myfuncy; function<void> myfuncz; myfuncx.functype mf1 = fn1; myfuncy.functype mf2 = fn2; myfuncz.functype mf3 = fn3; fn1(244); fn2(568, 1.891); fn3(); return exit_success; }
objects unknown until runtime reason need them class members. they're stored in std::map , need able specific item map , use it's function definition/prototype store pointer of function.
but kind of error:
||=== build: win32 release in sandbox (compiler: gnu gcc compiler) === .\src\testdummy.cpp||in function 'int main(int, char**)': .\src\testdummy.cpp|42|error: invalid use of 'using functype = void (*)(int)' .\src\testdummy.cpp|42|error: expected ';' before 'mf1' .\src\testdummy.cpp|43|error: invalid use of 'using functype = void (*)(int, float)' .\src\testdummy.cpp|43|error: expected ';' before 'mf2' .\src\testdummy.cpp|44|error: invalid use of 'using functype = void (*)()' .\src\testdummy.cpp|44|error: expected ';' before 'mf3' ||=== build failed: 6 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===
i've tried std::function, typedef etc. why this?
this wrong:
myfuncx.functype mf1 = fn1;
you can't use type alias normal member - it's declaration inside class' scope, similar typedef
s. work:
decltype(myfuncx)::functype mf1 = fn1;
Comments
Post a Comment