简体   繁体   English

将对象函数转换为函数指针

[英]Convert object function to function pointer

I'm trying convert a object function to function pointer but can't get it, i've done something like this, simple example: 我正在尝试将对象函数转换为函数指针,但无法获取它,我已经做了类似以下的简单示例:

typedef struct
{
    int v1;

    int DoSome(int a)
    {
        return v1 * a;
    }
} strx;


int main()
{
    strx a; // instance...
    a.v1 = 2;


    std::function<int(strx* instance, int value)> DoSome = std::mem_fn(&strx::DoSome);

    cout << DoSome(&a, 4) << endl; // 16 ok 

    int(*pDoSome)(strx* instance, int value) = (int(*)(strx*, int))std::mem_fn(&strx::DoSome); // syntax error

    // ptr method...
    pDoSome(&a ,4);

    return 0;
} 

and i have obtained something like: 而且我获得了类似的东西:

main.cpp [Error] invalid cast from type 'std::_Mem_fn' to type 'int ( )(strx , int)' main.cpp [错误]从类型'std :: _ Mem_fn'强制转换为类型'int( )(strx ,int)'

How i can do correctly the casting? 我如何正确进行铸造?

You can't. 你不能 This is why std::function is more flexible than pointers to functions. 这就是为什么std::function比指向函数的指针更灵活的原因。

How i can do correctly the casting? 我如何正确进行铸造?

You cannot. 你不能。 Object pointers and function pointers are totally different concepts. 对象指针和函数指针是完全不同的概念。 Only nullptr can be used to initialize both types of pointers. 只能使用nullptr来初始化两种类型的指针。 Otherwise, they are not guaranteed to be compatible. 否则,不能保证它们兼容。

I suggest sticking with the std::function . 我建议坚持使用std::function

If you must have a function pointer, you have to use a non-member function or a static member function of a class. 如果必须具有函数指针,则必须使用类的非成员函数或static成员函数。

Eg 例如

int doSomeFunction(strx* instance, int value)
{
   // Use instance any way you please.
   // ...
   //
   return 0;
}

int main()
{
    strx a; // instance...
    a.v1 = 2;

    int(*pDoSome)(strx* instance, int value) = doSomeFunction;

    // ptr method...
    pDoSome(&a ,4);

    return 0;
} 

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

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