Deducing a function pointer return type

折月煮酒 提交于 2019-11-27 03:22:31

问题


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


回答1:


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;
};


来源:https://stackoverflow.com/questions/18695564/deducing-a-function-pointer-return-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!