我有很多类型定义为 std::function<void(PARAMS)>
的类其中 PARAMS 特定于每个类。我需要根据参数的数量和第一个参数的类型进行专门化。我想使用 boost::function_traits
为此,但为了使用它,我需要拥有 std::function
的原始函数类型有问题。
例如,给定std::function<void(int,int)>
, 我想检索 void(int,int)
.
有没有办法以可移植的方式提取 native 类型?附带说明一下,我无权访问 C++11 功能。
最佳答案
要获取函数类型,可以使用偏特化:
template <typename T>
struct Detect;
template <typename F>
struct Detect<std::function<F>> {
typedef F Result;
};
现在当你得到一个未知的 std::function<?>
输入 T
, 你只需使用
typename Detect<T>::Result
(您可能希望将 Result
定义为 F *
,因为某些上下文(例如,字段类型)只允许指向函数的指针,而不是裸函数类型。
编辑:
要专注于参数的数量和第一个参数的类型,您需要 C++11 可变参数模板
template <typename T>
struct Detect;
template <typename R, typename A, typename... As>
struct Detect<std::function<R(A,As...)>> {
static constexpr auto numargs = 1 + sizeof...(As);
typedef R Result;
typedef A FirstArg;
};
或编写与上述等效的代码,为每个可能的参数数量使用单独的特化:
template <typename R, typename A1>
struct Detect<std::function<R(A1)>> {
enum { numargs = 1 };
typedef R Result;
typedef A1 FirstArg;
};
template <typename R, typename A1, typename A2>
struct Detect<std::function<R(A1,A2)>> {
enum { numargs = 2 };
...
};
...
关于c++ - 如何从 std::function 获取基本函数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12063239/