C++:接受任何带有一个参数的函数的模板?

发布于 2024-12-27 23:12:02 字数 399 浏览 2 评论 0原文

基本上,我希望能够将带有任何参数的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

待天淡蓝洁白时 2025-01-03 23:12:02

您可以将整个函数类型设置为模板参数。然后编译器可以使用输入参数推导模板参数。

template <typename F, typename T>
void foo (F func, const T& p)
{
    // do code
    func(p);
}

foo(&someFunc, someInt);

这还有一个优点就是可以支持函数对象。 (这也是标准库(“STL”)支持将函数传递给算法的方式。)

You could just make the whole function type a template parameter. Then the compiler can deduce the template parameters using the input arguments.

template <typename F, typename T>
void foo (F func, const T& p)
{
    // do code
    func(p);
}

foo(&someFunc, someInt);

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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文