Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free function with parameters, get return type

Tags:

c++

c++11

I have a function on which i'd like to have the variable that returns the computed value be automatically deduced from the return type of the function.

I have seen Decltype for return of a function for member functions and i know that with decltype(func()) var i can get the return type. But that only works for functions without a parameter. If I have a parameter i have to decltype(func(/* some dummy value convertible to argument type*/)) to get the return type.

is there any way of doing the above without needing to specify a dummy value?

auto func(int a) -> std::deque<decltype(a)> {

  // lots of code

  /* ideally */
  decltype(func)::return_type result;

  /* fill result*/

  return result;
}
like image 610
RedX Avatar asked Feb 16 '23 07:02

RedX


1 Answers

You need to specify the argument types, since different overloads can have different return types.

You can specify a dummy argument using declval:

#include <utility>

decltype(func(std::declval<ArgType>())) result;

or you can avoid giving a dummy value by using type traits:

#include <type_traits>

std::result_of<decltype(func), ArgType>::type result;
like image 161
Mike Seymour Avatar answered Feb 23 '23 19:02

Mike Seymour