我正在尝试使用std::function
和这个结合std::bind
,但我遇到了一些问题。
这有效:
#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 ()>
并且需要能够返回该函数;不只是称呼它。我预计用法会是这样的:
#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 (*)()
与绑定签名非常匹配。
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(*)()
。这在第一个示例中起作用的唯一原因是因为它happens成为一个void(*)()
起初。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)