Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deducing a function pointer return type

I think code will better illustrate my need:

template <typename F>
struct return_type
{
  typedef ??? type;
};

so that:

return_type<int(*)()>::type -> int
return_type<void(*)(int,int)>::type -> void

I know of decltype and result_of but they need to have arguments passed. I want to deduce the return type of a function pointer from a single template parameter. I cannot add the return type as a parameter, because that's exactly what I want to hide here...

I know there's a solution in boost, but I can't use it, and an attempt to dig it out from boost resulted in a spectacular failure (as it often does).

C++11 solutions welcome (as long as supported in VS2012).

like image 576
Kornel Kisielewicz Avatar asked Sep 09 '13 09:09

Kornel Kisielewicz


People also ask

What is the return type of function pointer?

Return Function Pointer From Function: To return a function pointer from a function, the return type of function should be a pointer to another function. But the compiler doesn't accept such a return type for a function, so we need to define a type that represents that particular function pointer.

Can function return function pointer in C?

Pointers in C programming language is a variable which is used to store the memory address of another variable. We can pass pointers to the function as well as return pointer from a function.

Can a pointer be a return type C++?

Use the std::string::data Function to Return Pointer From Function in C++ Function return types generally fall into three categories: value, reference, or pointer. All of them have their optimal use cases in which most of the performance is reached.


1 Answers

If you can use variadic templates (November '12 CTP), this should work:

template <class F>
struct return_type;

template <class R, class... A>
struct return_type<R (*)(A...)>
{
  typedef R type;
};

Live example.

If you can't use variadic templates, you'll have to provide specific specialisations for 0, 1, 2, ... parameters (by hand or preprocessor-generated).

EDIT

As pointed out in the comments, if you want to work with variadic functions as well, you'll have to add one extra partial specialisation (or one for each parameter count in the no-variadic-templates case):

template <class R, class... A>
struct return_type<R (*)(A..., ...)>
{
  typedef R type;
};
like image 142
Angew is no longer proud of SO Avatar answered Oct 20 '22 22:10

Angew is no longer proud of SO