简体   繁体   English

C ++ typedef函数定义为类成员,以后用作函数指针吗?

[英]C++ typedef function definition as a class member to use later for function pointer?

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. 它们存储在std :: map中,我需要能够从映射中获取特定项,并使用它的函数定义/原型存储函数的指针。

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? 我已经尝试过std :: function,typedef等。为什么我得到这个?

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 typedef s. 您不能将类型别名用作普通成员-这是类范围内的声明,类似于typedef This will work: 这将起作用:

decltype(myFuncX)::FuncType mf1 = fn1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM