推导函数指针的返回类型 [英] Deducing a function pointer return type

查看:111
本文介绍了推导函数指针的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为代码可以更好地说明我的需求:

I think code will better illustrate my need:

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

这样:

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

我知道 decltype result_of ,但他们需要传递参数。我想从单个模板参数推断出函数指针的返回类型。我不能将返回类型添加为参数,因为这正是我要隐藏的内容...

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

我知道boost中有解决方案,但是我做不到使用它,然后尝试从增强中挖掘出来的尝试会导致严重失败(通常如此)。

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解决方案(只要受支持)在VS2012中)。

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

推荐答案

如果您可以使用可变参数模板(12年11月CTP),则应该可以:

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

实时示例

如果不能使用可变参数模板,则必须为0、1、2 ...参数提供特定的专业化(由人工或由预处理程序生成)。

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

这篇关于推导函数指针的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆