如何定义和使用带有“可选参数”的 boost::function ?
我正在使用一个需要某种回调方法的类,因此我使用 boost::function 来存储函数指针。
我需要回调有一个可选参数,但我发现 boost::function 不允许我定义可选参数类型,所以我尝试了以下代码并且它起作用了..
//the second argument is optional
typedef boost::function< int (int, char*)> myHandler;
class A
{
public:
//handler with 2 arguments
int foo(int x,char* a) {printf("%s\n",a); return 0;};
//handler with 1 argument
int boo(int x) {return 1;};
}
A* a = new A;
myHandler fooHandler= boost::bind(&A::foo,a,_1,_2);
myHandler booHandler= boost::bind(&A::boo,a,_1);
char* anyCharPtr = "just for demo";
//This works as expected calling a->foo(5,anyCharPtr)
fooHandler(5,anyCharPtr);
//Surprise, this also works as expected, calling a->boo(5) and ignores anyCharPtr
booHandler(5,anyCharPtr);
我很震惊它起作用了,问题它应该有效吗?它合法吗?
有更好的解决方案吗?
I am using a class that needs some kind of callback method, so i'm using boost::function to store the function pointers.
i need the callback to have one optional argument, but i found out that boost::function won't let me define optional arguments kind of type, so i tried the following code and it worked..
//the second argument is optional
typedef boost::function< int (int, char*)> myHandler;
class A
{
public:
//handler with 2 arguments
int foo(int x,char* a) {printf("%s\n",a); return 0;};
//handler with 1 argument
int boo(int x) {return 1;};
}
A* a = new A;
myHandler fooHandler= boost::bind(&A::foo,a,_1,_2);
myHandler booHandler= boost::bind(&A::boo,a,_1);
char* anyCharPtr = "just for demo";
//This works as expected calling a->foo(5,anyCharPtr)
fooHandler(5,anyCharPtr);
//Surprise, this also works as expected, calling a->boo(5) and ignores anyCharPtr
booHandler(5,anyCharPtr);
I was shocked that it worked, question is should it work, and is it legit?
is there a better solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可以说是绑定中的类型安全漏洞 ->函数转换。
boost::bind 不返回 std::function 而是一个非常复杂类型的函数对象。在上面看到的情况下
,返回的对象具有类型
std::function 仅检查提供的函数对象是否“兼容”,在这种情况下,是否可以使用 int 调用 作为第一个参数,指向 char 的指针作为第二个参数。在检查 *boost::bind_t* 模板时,我们发现它确实有一个匹配的函数调用运算符:
在这个函数内,第二个参数最终被默默地丢弃。这是设计使然。来自文档:任何额外的参数都会被默默地忽略(...)
Arguably a type safety hole in the bind -> function conversion.
boost::bind doesn't return an std::function but a function object of a very complicated type. In the case of
as seen above, the returned object has type
std::function only checks that the supplied function object is "compatible", in this case, whether it is callable with an int as the first argument and a pointer to char as the second argument. Upon examining the *boost::bind_t* template, we see that it does indeed have a matching function call operator:
Inside this function the second argument ends up being silently discarded. This is by design. From the documentation: Any extra arguments are silently ignored (...)