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?
CodePudding user response:
- If you want
add
to 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::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.
CodePudding user response:
The code you posted does not seem to compile. Have you tried something like the following?
#include <stdio.h>
#include <iostream>
int thirds(int a){
return a 1;
}
template <typename T, typename B>
int hello(T x, B y , int (*ptr)(int)){
int first = x 1;
int second = y 1;
int third = ptr(first);
return first second third;
}
int add(){
int (*ptr)(int) = &thirds;
return hello(1, 1, ptr); //from here pass a number
}
int main()
{
std::cout << add();
return 0;
}
In addition, I would suggest looking into std::function and lambdas.