【问题标题】:How to pass a pointer to a static function as argument to another static function from inside a static function in C++如何将指向静态函数的指针作为参数从 C++ 中的静态函数内部传递给另一个静态函数
【发布时间】:2014-06-26 08:47:27
【问题描述】:

如何将指向静态函数的指针作为参数从静态函数内部传递给另一个静态函数,它们都在同一个类中?我正在使用 VisualStudio 2010。 我的代码大致是这样的:

//SomeClass.h
class SomeClass
{
    public:
        static AnotherClass* doSomething(AnotherClass*, AnotherClass*);
        static AnotherClass* doSomethingElse(AnotherClass*, AnotherClass*);

    private:
        typedef float (SomeClass::*SomeOperation)(float, float);
        static AnotherClass* apply(AnotherClass*, 
                                   AnotherClass*, 
                                   SomeOperation);

        static float SomeClass::operationA(float, float);
        static float SomeClass::operationB(float, float);
};

//SomeClass.cpp
AnotherClass* SomeClass::doSomething(AnotherClass* a, AnotherClass* b)
{
    return apply(a, b, &SomeClass::operationA);
}

AnotherClass* SomeClass::doSomethingElse(AnotherClass* a, AnotherClass* b)
{
    return apply(a, b, &SomeClass::operationB);
}

AnotherClass* apply(AnotherClass* a, 
                    AnotherClass* b, 
                    SomeOperation op)
{
    /* Some sanity checking and a lot of loop stuff which is the same
     * for all operations a, b, c ... */

}

我尝试了不同的变体,但不断收到编译器错误,例如:

C2664“SomeClass::apply”:无法从“SomeClass::SomeOperation”中的“float (__cdecl *)(float, float)”转换参数 3。

有谁知道我做错了什么以及如何解决这个问题?

【问题讨论】:

  • 我相信您想切换到C++11,这将为您提供anonymous functionsclosures 实现。考虑升级你的编译器:最近的GCC -e.g. 4.8 或 4.9- 很好地支持 C++11。
  • @Basile 即“使用 jQuery”?
  • @LightnessRacesinOrbit:或者“使用 Ocaml”或“使用 Common Lisp”......

标签: c++ static function-pointers argument-passing


【解决方案1】:

静态成员函数只是一个函数;您不使用指向成员语法的指针。

所以不是

typedef float (SomeClass::*SomeOperation)(float, float);

你想要

typedef float (*SomeOperation)(float, float);

您可以只传递operationA 而不是&SomeClass::operationA

【讨论】:

  • 我接受这个作为正确答案,因为解释了为什么必须省略“SomeClass::”部分。再次感谢大家的快速解答。
【解决方案2】:

改变这个:

private:
    typedef float (SomeClass::*SomeOperation)(float, float);

到这里:

public:
    typedef float (*SomeOperation)(float, float);

或者你可以简单地在类外声明typedef float (*SomeOperation)(float, float)...

【讨论】:

    【解决方案3】:

    从 typedef 中删除 SomeClass::

    示例中有各种语法错误,但在修复它们并这样做之后,我可以编译您的代码。

    【讨论】:

    • 是的,就是 tyvm!我不确定它是 VS2010 编译器还是一般的东西,但我在程序的另一点有另一个指向非静态方法的指针的 typdef,并且“SomeClass::”是必需的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多