C++ 有没有办法在编译时迭代函数参数类型?我想做这样的事情:
struct null_type {};
float foo(int, bool, char);
get_param_type<foo, 0>::type float_var; // return type
get_param_type<foo, 1>::type int_var; // first arg type
get_param_type<foo, 2>::type bool_var; // second arg type
get_param_type<foo, 3>::type char_var; // third arg type
get_param_type<foo, 4>::type null_type_var;
Run Code Online (Sandbox Code Playgroud)
您可以轻松地自己编写此代码。首先,将函数参数类型打包到一个元组中:
#include <tuple>
template <typename> struct FnArgs;
template <typename R, typename ...Args>
struct FnArgs<R(Args...)>
{
using type = std::tuple<Args...>;
};
Run Code Online (Sandbox Code Playgroud)
现在您可以使用标准元组 API 来访问元素:
using FT = FnArgs<decltype(foo)>::type;
std::tuple_element<0, FT> x;
Run Code Online (Sandbox Code Playgroud)
如果您需要的话,可以轻松添加对成员函数指针的进一步专门化。
(您无法轻松绕过decltype,因为目前还没有非类型模板参数的类型推导。)
| 归档时间: |
|
| 查看次数: |
711 次 |
| 最近记录: |