C++:接受任何带有一个参数的函数的模板?
基本上,我希望能够将带有任何参数的 function_A 传递给 T_function,以便 T_function 可以执行一些命令,然后调用传入的函数
这就是我想出的(这可能使我的目标更clear) :
template <typename t_return, typename t_param>
void foo(t_return (*func)(t_param), t_param p)
{
//do code
func(p);
}
foo<void, int>(&someFunc, someInt);
上面的代码效果很好,但看起来很麻烦。我也不确定它有多万无一失。有稍微了解一点的人有进步吗? 我尝试在网上查找此内容,但事实证明很难搜索。
Basically, I would like to be able to be able to pass a function_A with any parameter to T_function, so that T_function could execute some commands, then call the passed-in function
This is what I came up with (which might make my goal more clear) :
template <typename t_return, typename t_param>
void foo(t_return (*func)(t_param), t_param p)
{
//do code
func(p);
}
foo<void, int>(&someFunc, someInt);
The above code works great, but it seems bothersome. I'm also not sure how fool-proof it is. Does anyone with a little more understanding have an improvement?
I've tried looking this up online, however it has proved difficult to search for.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将整个函数类型设置为模板参数。然后编译器可以使用输入参数推导模板参数。
这还有一个优点就是可以支持函数对象。 (这也是标准库(“STL”)支持将函数传递给算法的方式。)
You could just make the whole function type a template parameter. Then the compiler can deduce the template parameters using the input arguments.
This also has an advantage that function objects can be supported. (This is also how the standard library ("STL") supports passing functions to the algorithms.)