Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to correctly pass a function with parameters to another function?

I have the following code to demonstrate a function been called inside another function.

The below code works correctly:

#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;
}

Now I want to pass one number as a parameter from add function ie into thirds function (thirds(6)).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am trying this way:

#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;
}

My expected output is:

11

But It is not working. Please can someone show me what I am doing wrong?

>Solution :

  1. If you want add to pass a value to hello, to be passed to the function given by the pointer ptr, you have to add a separate parameter.
  2. In c++ it is usually advised to use std::function instead of old c style funtion pointers.

A complete example:

#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;
}

Output:

11

Note: another solution could be to use std::bind to create a callable from thirds and the argument 6. But I think the solution above is more simple and straightforward.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading