Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, is it possible to get the return type of a function in order to declare a variable without calling that function?

Tags:

int myfun() {   return 42; } 

I know I can write

auto myvar = myfun(); 

but what if I just want to declare myvar (without using a common typedef)?

the_type_returned_by_myfun myvar; 

What can be written instead of the_type_returned_by_myfun?

like image 566
Alessandro Jacopson Avatar asked Dec 21 '11 16:12

Alessandro Jacopson


People also ask

Does every function has a return type in C?

In C, all functions must be written to return a specific TYPE of information and to take in specific types of data (parameters). This information is communicated to the compiler via a function prototype. The function prototype is also used at the beginning of the code for the function.

Can we call a function with its return type?

What happens when you call a function with return value without assigning it to any variable? The return value of a function need not be used or assigned. It is ignored (usually quietly). The function still executes and its side effects still occur.

Can a function be defined without a return statement?

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.

Can a function return a function in C?

Yes any function can return a function pointer.


1 Answers

You can use decltype.

decltype(myfun()) myvar; // or typedef decltype(myfun()) myfun_ret; myfun_ret myvar2; 

And if the function happens to have parameters, you can produce fake parameters with std::declval.

#include <utility>  int my_other_fun(foo f); typedef decltype(myfun(std::declval<foo>())) my_other_fun; 
like image 138
Xeo Avatar answered Oct 06 '22 00:10

Xeo