Pergunta

I need to have a class that stores a function definition/prototype as a class member in order to use it later to get function pointers based on that 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 are unknown until runtime which is the reason I need them to be class members. They're stored in an std::map and I need to be able to get a specific item from the map and to use it's function definition/prototype to store the pointer of a function.

But I always get this 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 with std::function, typedef etc. Why do I get this?

Foi útil?

Solução

This is wrong:

myFuncX.FuncType mf1 = fn1;

You can't use a type alias as a normal member - it's a declaration inside class' scope, similar as typedefs. This will work:

decltype(myFuncX)::FuncType mf1 = fn1;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top