c++ - 将对象函数转换为函数指针

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

我正在尝试将一个对象函数转换为函数指针但无法获取它,我已经做了类似这样的事情,简单的例子:

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 [Error] invalid cast from type 'std::_Mem_fn' to type 'int ()(strx, int)'

我怎样才能正确地进行转换?

最佳答案

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

关于c++ - 将对象函数转换为函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43127781/

相关文章:

c++ - 即使没有子类重写一个方法,它也会被虚拟调用吗?

c++ - QTreeView可以加入QDockWidget吗

c++ - 收集多项式表达式中不相交的项

C++ 调试窗口显示“<incomplete type> for string variable

c++ - 为什么 C++ 不像 HTML/HTML5 那样移动到 'unversioned model'?

c++ - Windows 与 Linux - C++ 线程池内存使用情况

c++ - 使用 constexpr 函数作为模板参数是否有效?

c++ - 关于太多模板标题的警告

c++ - 使用静态常量初始化 unique_ptr 时出现 undefined reference 错误

c++ - 即使复制构造函数不可用,返回仅移动类型也会编译