c++ - 如何正确地将带参数的函数传递给另一个函数?

标签 c++ function c++11 callback c++17

我有以下代码来演示在另一个函数中调用一个函数。

下面的代码可以正常工作:

#include <iostream>

int thirds()
{
    return 6 + 1;
}
template <typename T, typename B>
int hello(T x, B y , int (*ptr)() ){
    
    int first = x + 1;
    int second = y + 1;
    int third = (*ptr) (); ;
    
    return first + second + third;
}
int add(){
    
     int (*ptr)() = &thirds;
    return hello(1,1, thirds);
}
int main()
{
    std::cout<<add();
    return 0;
}

现在我想将一个数字作为参数从 add 函数传递给 thirds 函数 (thirds(6))。

我正在尝试这种方式:

#include <iostream>

int thirds(int a){
    return a + 1;
}

template <typename T, typename B>
int hello(T x, B y , int (*ptr)(int a)() ){
    
    int first = x + 1;
    int second = y + 1;
    int third = (*ptr)(a) (); ;
    
    return first + second + third;
}

int add(){
    
     int (*ptr)() = &thirds;
    return hello(1,1, thirds(6)); //from here pass a number
}

int main()
{
    
    std::cout<<add();

    return 0;
}

我的预期输出是:

11

但它不起作用。有人可以告诉我我做错了什么吗?

最佳答案

  1. 如果你想让add传递一个值给hello,传递给指针ptr给定的函数,你必须添加一个单独的参数。
  2. 在c++中通常建议使用std::function而不是旧的 C 风格函数指针。

一个完整的例子:

#include <iostream>
#include <functional>

int thirds(int a) 
{
    return a + 1;
}

template <typename T, typename B>
//------------------------------------------------VVVVV-
int hello(T x, B y, std::function<int(int)> func, int a) 
{
    int first = x + 1;
    int second = y + 1;
    int third = func(a);
    return first + second + third;
}

int add() 
{
    std::function<int(int)> myfunc = thirds;
    return hello(1, 1, myfunc, 6);
}

int main() 
{
    std::cout << add();
    return 0;
}

输出:

11

注意:另一种解决方案是使用 std::bindthirds 和参数 6 创建一个可调用对象。但我认为上面的解决方案更简单直接。

关于c++ - 如何正确地将带参数的函数传递给另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74413185/

相关文章:

c++ - 视觉 C++ : No devirtualization in obvious cases?

c++ - C++ 中带有虚函数调用的构造函数

c++ - 无法分配功能指针的2D数组

C 在 void 函数之后由指针发送的数组的值被修改

c++ - 关于 new 和 delete 的使用,以及 Stroustrup 的建议

c++ - 在函数中使用引用或返回

c++ - 比较 descriptor.type 和 descriptor.cols 后的 OpenCV 段错误

PostgreSQL 函数 : get id of updated or inserted row

c++ - std::begin 和 R 值

c++ - C++ - 保存值时出现问题 - 保存后值发生变化