Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use function return type as an argument in declaration of another function in C++?

I want something like this:

std::tuple<int, bool, double> MyFunction_1 (void);  void MyFunction_2 (decltype (MyFunction_1) &params); 

Obviously, in this example a code pointer to function would be passed.

I want to have the equivalent of this:

void MyFunction_2 (std::tuple<int, bool, double>  &params); 

Is it possible to do so?

like image 919
Dmitrii Motorygin Avatar asked Oct 15 '18 07:10

Dmitrii Motorygin


People also ask

Can the return value from a function call be used as the argument to another function call?

So yes there are stack or local variables to a specified scope resolution.

Can a function be an argument for another function in C?

Till now, we have seen that in C programming, we can pass the variables as an argument to a function. We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.

What do you call a function that is used as an argument of another function?

A variable defined inside a function. A local variable can only be used inside its function. parameter. A name used inside a function to refer to the value passed as an argument.

Can we use a function as a parameter of another function?

Yes, you can. In Javascript functions can be passed as an argument to an another function and functions can also be returned from a fuction. Such type of functions are called Higher Order functions.


2 Answers

decltype (MyFunction_1) will give you the type of MyFunction_1 (i.e. the function type std::tuple<int, bool, double> ()), you need to emulate a function calling 1 (via adding ()) to get the return type (i.e. std::tuple<int, bool, double>), e.g.

void MyFunction_2 (decltype (MyFunction_1()) &params); //                                       ^^ 

1 The expression is evaluated at compile-time, the function won't be called at run-time actually.

like image 54
songyuanyao Avatar answered Oct 28 '22 16:10

songyuanyao


The type of MyFunction_1 is not std::tuple<int, bool, double> - informally you can think of it as a function pointer. In fact &MyFunction_1 decays to itself and is certainly a pointer.

So decltype(MyFunction_1) is not what you want.

The solution is to write decltype(MyFunction_1()). The type of MyFunction_1() is std::tuple<int, bool, double>. Note that this doesn't actually call the function; it's rather like sizeof in that respect.

like image 20
Bathsheba Avatar answered Oct 28 '22 16:10

Bathsheba