Dmitrii Motorygin
Dmitrii Motorygin

Reputation: 516

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?

Upvotes: 31

Views: 2510

Answers (3)

jf12
jf12

Reputation: 31

using RetType = std::invoke_result<decltype(f)>::type;

Play with it : https://gcc.godbolt.org/z/AE7lj_

Upvotes: 3

songyuanyao
songyuanyao

Reputation: 173044

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.

Upvotes: 35

Bathsheba
Bathsheba

Reputation: 234875

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.

Upvotes: 16

Related Questions