使用 boost::hana 获取函数参数的类型

Get the type of a function parameter with boost::hana

本文关键字:参数 函数 类型 获取 boost hana 使用      更新时间:2023-10-16

我知道如何以旧方式获取函数参数的类型,但我想知道是否有一种很好的新方法可以使用 Hana 做到这一点?例如,我想要这样的东西:

struct foo {
    int func(float);
};
auto getFuncType(auto t) -> declval<decltype(t)::type>()::func(TYPE?) {}
getFunType(type_c<foo>); // should equal type_c<float> or similar

我如何在这里获得TYPE

编辑 6/21/2016 - 对库的当前版本(0.4)进行了细微更改。

我是CallableTraits的作者,@ildjarn上面提到的库(尽管它尚未包含在Boost中)。arg_at_t元函数是我知道从成员函数、函数、函数指针、函数引用或函数对象/lambda 获取参数类型的最佳方式。

请记住,库目前正在进行重大更改,并且链接的文档有些过时(即使用风险自负)。如果你使用它,我建议克隆开发分支。对于您正在寻找的功能,API 几乎肯定不会更改。

对于成员函数指针,arg_at_t<0, mem_fn_ptr>别名等效于 decltype(*this) ,以考虑隐式this指针。因此,对于您的情况,您将这样做:

#include <type_traits>
#include <callable_traits/arg_at.hpp>
struct foo {
    int func(float);
};
using func_param = callable_traits::arg_at_t<1, decltype(&foo::func)>;
static_assert(std::is_same<func_param, float>::value, "");
int main(){}

然后,您可以将其放入boost::hana::type或用例所需的任何内容中。

现场示例