【问题标题】:Convert object function to function pointer将对象函数转换为函数指针
【发布时间】:2017-03-30 20:32:16
【问题描述】:

我正在尝试将对象函数转换为函数指针,但无法得到它,我做过类似的事情,简单的例子:

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

我得到了类似的东西:

main.cpp [错误] 从类型 'std::_Mem_fn' 到类型 'int ()(strx, int)' 的无效转换

我怎样才能正确地进行铸造?

【问题讨论】:

  • std::function&lt;strx* instance, int value&gt; 无效。你的意思是std::function&lt;int (strx*, int)&gt;
  • @aschepler 是的,我已经修好了,谢谢。
  • 你不需要在 C++ 中使用typedef。只需使用struct strx { ... },因为类和结构名称会自动成为类型。

标签: c++ c++11 c++14


【解决方案1】:

你不能。这就是std::function 比函数指针更灵活的原因。

【讨论】:

    【解决方案2】:

    我怎样才能正确地进行铸造?

    你不能。对象指针和函数指针是完全不同的概念。只有nullptr 可以用来初始化这两种类型的指针。否则,不能保证它们是兼容的。

    我建议坚持使用std::function

    如果你必须有一个函数指针,你必须使用一个非成员函数或者一个类的static成员函数。

    例如

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

    【讨论】:

    • 好的,我不能这样做,因为我需要指针函数来绕道,但非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2016-06-03
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多