Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to determine return type of function

Given a very simple, but lengthy function, such as:

int foo(int a, int b, int c, int d) {     return 1; }  // using ReturnTypeOfFoo = ??? 

What is the most simple and concise way to determine the function's return type (ReturnTypeOfFoo, in this example: int) at compile time without repeating the function's parameter types (by name only, since it is known that the function does not have any additional overloads)?

like image 830
Cybran Avatar asked Dec 07 '18 16:12

Cybran


People also ask

How do you determine the return type of a function?

function myFunction(a: number, b: number): void { console. log(a); console. log(b); } // 👇️ type T = void type T = ReturnType<typeof myFunction>; If the function might return values of multiple types, its return type will be a union type.

How do you find the return type of a function in C++?

Most simple and concise is probably: template <typename R, typename... Args> R return_type_of(R(*)(Args...)); using ReturnTypeOfFoo = decltype(return_type_of(foo));

How do you decide that a function must return a value?

A function that returns a value is called a value-returning function. A function is value-returning if the return type is anything other than void . A value-returning function must return a value of that type (using a return statement), otherwise undefined behavior will result.

What is return type of a function mean?

The result of a function is called its return value and the data type of the return value is called the return type. If a function declaration does not specify a return type, the compiler assumes an implicit return type of int .


1 Answers

You can leverage std::function here which will give you an alias for the functions return type. This does require C++17 support, since it relies on class template argument deduction, but it will work with any callable type:

using ReturnTypeOfFoo = decltype(std::function{foo})::result_type; 

We can make this a little more generic like

template<typename Callable> using return_type_of_t =      typename decltype(std::function{std::declval<Callable>()})::result_type; 

which then lets you use it like

int foo(int a, int b, int c, int d) {     return 1; }  auto bar = [](){ return 1; };  struct baz_  {      double operator()(){ return 0; }  } baz;  using ReturnTypeOfFoo = return_type_of_t<decltype(foo)>; using ReturnTypeOfBar = return_type_of_t<decltype(bar)>; using ReturnTypeOfBaz = return_type_of_t<decltype(baz)>; 
like image 169
NathanOliver Avatar answered Sep 19 '22 04:09

NathanOliver