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

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

我知道如何用旧方法获取函数参数的类型,但我想知道是否有一种新方法可以用 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

2016 年 6 月 21 日编辑 - 为匹配当前版本的库 (0.4) 而进行的小改动。

我是 CallableTraits 的作者,这是 @ildjarn 上面提到的库(尽管它尚未包含在 Boost 中)。 arg_at_t 元函数是我所知道的从成员函数、函数、函数指针、函数引用或函数 object/lambda.

获取参数类型的最佳方法

请记住,库目前正在发生重大变化,链接的文档有些过时(即使用风险自负)。如果你使用它,我建议克隆 develop branch。对于您正在寻找的功能,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 或您的用例需要的任何内容。

Live example