C++17: Most simple way to determine return type of function

  • A+
Category:Languages

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)?

 


Most simple and concise is probably:

template <typename R, typename... Args> R return_type_of(R(*)(Args...));  using ReturnTypeOfFoo = decltype(return_type_of(foo)); 

Note that this won't work for function objects or pointers to member functions. Just functions, that aren't overloaded or templates, or noexcept.

But this can be extended to support all of those cases, if so desired, by adding more overloads of return_type_of.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: