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)).
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 :
- If you want
addto pass a value tohello, to be passed to the function given by the pointerptr, you have to add a separate parameter. - In c++ it is usually advised to use
std::functioninstead 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.