在设置函数指针之前绑定参数?
我想尝试一些东西,并在我们的动态库 API 包装器之一中统一一些样板代码。
本质上,我想做以下事情:
typedef bool (*MyFPtrT)(long id, std::string const& name);
typedef boost::function<bool (long id, std::string const& name)> MyFObjT;
...
...
MyFPtrT pDllFun = NULL;
long x = 42; string s = "Answer"; // API input, not hardcoded
MyFObjT f = boost::bind(pDllFun, x, s);
...
return Call(f);
...
template<FT>
bool Call(FT f) {
...
MyFPtrT pDllFun = (MyFunPtr)::GetProcAddress(...);
f.setFunctionPointerButLeaveBoundParameters(pDllFun); // <- how??
// Now call the correctly rigged up function object:
return f();
}
这可能吗? (使用Boost还是其他?)(C++03)
I would like to try something out and unify some boilerplate code in one of our dynamic library API wrappers.
Essentially, I would like to do the following:
typedef bool (*MyFPtrT)(long id, std::string const& name);
typedef boost::function<bool (long id, std::string const& name)> MyFObjT;
...
...
MyFPtrT pDllFun = NULL;
long x = 42; string s = "Answer"; // API input, not hardcoded
MyFObjT f = boost::bind(pDllFun, x, s);
...
return Call(f);
...
template<FT>
bool Call(FT f) {
...
MyFPtrT pDllFun = (MyFunPtr)::GetProcAddress(...);
f.setFunctionPointerButLeaveBoundParameters(pDllFun); // <- how??
// Now call the correctly rigged up function object:
return f();
}
Is this possible? (With Boost or otherwise?) (C++03)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为不能直接这样做,因为
bind
创建一个新对象,该对象通过引用获取函数对象和参数,并且您无法重新绑定引用。但是,您可以轻松地使用可重新分配的函数指针编写自己的模板化仿函数包装器:
[编辑:] 请检查下面的注释;在构造函数中保存 const 引用所采用的引用可能会被危险地滥用,因此请小心,或者如果您愿意,可以按值保存
a
和b
。[/]现在您可以初始化尽早使用参数的仿函数:
然后分配一个函数指针并调用:
您甚至可以用以下方式替换调用运算符:
然后使用函数指针作为参数调用仿函数:
在这种情况下,您不需要返回类型为不再是固定参数,但现在你得不到无效调用运算符。任你挑选。
I don't think it can be done directly like that, because
bind
creates a new object that takes the function object and the arguments by reference, and you can't rebind references.However, you can easily enough write your own templated functor wrapper with a reassignable function pointer:
[Edit:] Do check the comments below; holding references taken by const reference in the constructor can be dangerously abused, so be careful, or save
a
andb
by value if you prefer.[/]Now you can initialize the functor with the arguments early:
Then assign a function pointer and call:
You could even replace the call operator by this:
And then invoke the functor with the function pointer as the argument:
In that case you don't need the return type as a fixed parameter any longer, but now you don't get a nullary call operator. Take your pick.
似乎以下内容可能有效:
是的,那里有一些危险的参考资料。特别是,
f
保留对pDllFun
的引用。这可以很容易地缓解:将两者打包在一个类中,因此生命周期显然是相同的。Seems the following might work:
Yeah, there are some dangerous references around there. In particular,
f
keeps a reference topDllFun
. This can be mitigated fairly easy: pack the two in a single class, so the lifetimes are obviously identical.