[英]Deducing a function pointer return type
我认为代码会更好地说明我的需要:
template <typename F>
struct return_type
{
typedef ??? type;
};
以便:
return_type<int(*)()>::type -> int
return_type<void(*)(int,int)>::type -> void
我知道decltype
和result_of
但他们需要通过 arguments。 我想从单个模板参数中推断出 function 指针的返回类型。 我不能将返回类型添加为参数,因为这正是我想在这里隐藏的内容......
我知道在 boost 中有一个解决方案,但我不能使用它,并且试图从 boost 中挖掘它导致了一个惊人的失败(正如它经常发生的那样)。
欢迎C++11解答(只要VS2012支持)。
如果你可以使用可变参数模板(11月'12 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++17,有一个有趣的选项。 但是,语法与最初要求的有点不同,但结果(类型)是相同的。
首先,我们需要一个助手 function。正如您在此处看到的,function 接受一个 function 指针并返回一个类型为 R 的 object。我们只需要一个 decltype 语句,因此这个 8834004065898 永远不会被称为足够的前向声明, .
template<typename R, typename... ARGS>
static R return_type(R (*)(ARGS...)); // forward declaration only for decltype
诀窍是提供 function 指针作为模板自动参数,它被转发到 decltype 语句:
template<auto FUNCTION_POINTER>
using ReturnType = decltype(return_type(FUNCTION_POINTER));
现在很容易得到返回类型:
#include <iostream>
#include <type_traits>
template<typename R, typename... ARGS>
static R return_type(R (*)(ARGS...)); // forward declaration only for decltype
template<auto FUNCTION_POINTER>
using ReturnType = decltype(return_type(FUNCTION_POINTER));
int func1(char c, int i, long l); // also here only forward declarations needed
void func2(unsigned u, float f);
double func3(bool b);
int main()
{
std::cout << std::is_same_v<int, ReturnType<func1>> << std::endl;
std::cout << std::is_same_v<void, ReturnType<func2>> << std::endl;
std::cout << std::is_same_v<double, ReturnType<func3>> << std::endl;
std::cout << std::is_same_v<void, ReturnType<func1>> << std::endl;
}
您可以在 Wandbox 中尝试完整的示例: https://wandbox.org/permlink/5akL0MQDoDuJlQNY
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.