我需要编写一个函数 ( f),它接受带有通用回调参数的std::function( )。g在函数中f,当调用回调时,应该执行一些额外的代码。因此,我需要根据通用回调参数创建一个带有签名的 lambda。我的模板技能在这里失败了。
所以基本上,在下面的代码片段中, 和 都g1应该g2可以用作 的输入f:
void g1(std::function<void()> cb)
{
// do stuff, call callback
cb();
}
void g2(std::function<void(int)> cb)
{
cb(1);
}
template<typename TFunc, typename TCb>
void f(TFunc g, TCb handler)
{
// in some way intercept the callback from g to do additional stuff when callback arrives
g([handler](int i) { // this only works for g2 now, needs to be generic
// Do the extra stuff here before calling final callback
// Call final callback with same signature as g1 (or g2) callback
handler(i);
});
}
void main()
{
f(g1, [](){});
f(g2, [](int){});
}
Run Code Online (Sandbox Code Playgroud)
我不确定这是否是您所需要的,但也许您可以使用它作为起点...这需要 C++14
g([handler](auto&&... args ) {
// Do the extra stuff here before calling final callback
// Call final callback with same signature as g1 (or g2) callback
handler(std::forward<decltype(args)>(args)...);
});
Run Code Online (Sandbox Code Playgroud)
完整示例在这里: https: //godbolt.org/z/xranbfrEE
如果您可以使用 C++20,则可以使用新的 lambda 模板参数:
g([handler]<typename... Args> (Args&&... args ) {
handler(std::forward<Args>(args)...);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
159 次 |
| 最近记录: |