使用std :: bind时,从std :: function获取函数指针 [英] Get function pointer from std::function when using std::bind

查看:1596
本文介绍了使用std :: bind时,从std :: function获取函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 std :: function std :: bind ,但我' m有一些问题。

I'm trying to use std::function in conjunction with std::bind, but I'm having some problems.

这样做:

#include <functional>
#include <iostream>

void print() {
    std::cout << 2;
}

int main() {
    std::function<void ()> foo = print;
    (*foo.target<void (*)()>())(); //prints 3
}

这会在 main :

#include <functional>
#include <iostream>

void print (int i) {
    std::cout << i;
}

int main() {
    std::function<void ()> foo = std::bind (print, 2);
    (*foo.target<void (*)()>())();
}

我真的拿着 std :: function ; void()> 并且需要能够返回函数;不只是调用它。我期望的用法将是这样:

I'm really holding the std::function<void ()> and need to be able to return the function; not just call it. I expect the usage would be something like this:

#include <functional>
#include <iostream>

void print (int i) {
    std::cout << i;
}

int main() {
    Container c (std::bind (print, 2));

    //I would expect the original
    c.func() (3); //prints 3

    if (c.func() == print) /* this is what I'm mostly getting at */
}

有没有办法获得原始函数返回它,或者一个替代?它也与返回类型冲突,因为 void(*)()相当匹配绑定的签名。

Is there any way to get the original function to return it, or an alternative? It does kind of conflict with the return type as well, as void (*)() matches the bound signature quite nicely.

推荐答案

这是完全不可能的。 std :: function 存在的全部原因是函数指针吸引恐怖,永远不应该被任何人使用,再次,除了注定的灵魂轴承

This is quite impossible. The whole reason that std::function exists is that function pointers suck horrifically and should never, ever, be used by anyone, ever again, except for the doomed souls bearing the Burning Standards of Hell C interoperation, because they cannot handle functions with state.

A std :: function< void() )> 在一般情况下不能转换为 void(*)()。在第一个示例中工作的唯一原因是因为最初是 void(*)()

A std::function<void()> cannot, in the general case, be converted to a void(*)(). The only reason this works in the first example is because it happens to be a void(*)() originally.

这篇关于使用std :: bind时,从std :: function获取函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆