Search code examples
c++boostc++14boost-hana

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


I know how to get the type of a function's parameter the old way, but I was wondering if there is a nice new way to do it with Hana? For example, I want something like this:

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

How do I get the TYPE here?


Solution

  • Edit 6/21/2016 - Minor changes to match current version of library (0.4).

    I'm the author of CallableTraits, the library mentioned above by @ildjarn (although it is not yet included in Boost). The arg_at_t metafunction is the best way that I know to get the parameter type from a member function, function, function pointer, function reference, or function object/lambda.

    Please keep in mind that the library is currently undergoing significant changes, and that the linked documentation is somewhat outdated (i.e. use at your own risk). If you use it, I recommend cloning the develop branch. For the feature you are seeking, the API will almost certainly not change.

    For member function pointers, arg_at_t<0, mem_fn_ptr> aliases the equivalent of decltype(*this), to account for the implicit this pointer. So, for your case, you would do 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(){}
    

    Then, you can put it into a boost::hana::type or whatever your use case requires.

    Live example