【问题标题】:C++ typedef function definition as a class member to use later for function pointer?C ++ typedef函数定义为类成员,以后用于函数指针?
【发布时间】:2014-03-23 15:20:44
【问题描述】:

我需要一个将函数定义/原型存储为类成员的类,以便以后使用它来获取基于该定义的函数指针。

#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;
}

对象在运行时之前是未知的,这就是我需要它们成为类成员的原因。它们存储在 std::map 中,我需要能够从地图中获取特定项目并使用它的函数定义/原型来存储函数的指针。

但我总是遇到这种错误:

||=== 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)) ===

我已经尝试过 std::function、typedef 等。为什么会得到这个?

【问题讨论】:

  • 好的。你有问题吗?
  • sorry deviantfan 我在选择提交问题时按了 Enter,但我没有发布问题。

标签: c++ function class member definition


【解决方案1】:

这是错误的:

myFuncX.FuncType mf1 = fn1;

您不能将类型别名用作普通成员 - 它是类范围内的声明,类似于 typedefs。这将起作用:

decltype(myFuncX)::FuncType mf1 = fn1;

【讨论】:

  • 谢谢 :) 工作就像一个魅力。
猜你喜欢
  • 2016-05-12
  • 1970-01-01
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 2014-11-12
  • 1970-01-01
相关资源
最近更新 更多