我认为代码会更好地说明我的需求:
template <typename F>
struct return_type
{
typedef ??? type;
};
这样:
return_type<int(*)()>::type -> int
return_type<void(*)(int,int)>::type -> void
我知道 decltype
和 result_of
但它们需要传递参数。我想从单个模板参数中推断出函数指针的返回类型。我不能将返回类型添加为参数,因为这正是我想在这里隐藏的内容...
我知道在 boost 中有一个解决方案,但我不能使用它,并且试图从 boost 中挖掘它导致了一个惊人的失败(正如它经常发生的那样)。
欢迎使用 C++11 解决方案(只要在 VS2012 中受支持)。
最佳答案
如果您可以使用可变参数模板(2012 年 11 月 CTP),这应该可行:
template <class F>
struct return_type;
template <class R, class... A>
struct return_type<R (*)(A...)>
{
typedef R type;
};
如果您不能使用可变参数模板,则必须为 0、1、2 ... 参数(手动或预处理器生成)提供特定的特化。
编辑
正如评论中所指出的,如果您还想使用可变函数,则必须添加一个额外的偏特化(或者在无可变模板的情况下为每个参数计数添加一个):
template <class R, class... A>
struct return_type<R (*)(A..., ...)>
{
typedef R type;
};
关于c++ - 推导函数指针返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18695564/