Can you extract types from template parameter function signature

前端 未结 1 1909
北恋
北恋 2021-02-06 08:23

Is there a way that I can extract the types from a function signature in the form foo(bar) and get access to just foo or bar. So if I have

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-06 08:40

    Here is a very basic solution that works for functions accepting one parameter( it seems you are placing this constraint in the question, but a generalized solution is quite easy to provide, as shown in the following):

    template
    struct type; // You can leave this undefined, because the template is
                 // supposed to be instantiated with a function type, and
                 // that is matched by the specialization below.
    
    template
    struct type
    {
        // Just use R and Args as you wish here..
    };
    

    Here is a possible example (live demo on Coliru):

    #include 
    
    template
    struct signature;
    
    template
    struct signature
    {
        using return_type = R;
        using argument_type = Arg;
    };
    
    int main()
    {
        using ret = signature::return_type;
        using arg = signature::argument_type;
    
        static_assert(std::is_same{}, "!");
        static_assert(std::is_same{}, "!");
    }
    

    In case you are interested in a more general solution for the variadic case, this is probably what you're looking for:

    #include 
    
    struct type; // You can leave this undefined, because the template is
                 // supposed to be instantiated with a function type, and
                 // that is matched by the specialization below.
    
    template
    struct type
    {
        // Just use R and Args... as you with here..
    };
    

    And here is a possible usage example (live demo on Coliru):

    #include 
    #include 
    
    template
    struct signature;
    
    template
    struct signature
    {
        using return_type = R;
        using argument_type = std::tuple;
    };
    
    int main()
    {
        using ret = signature::return_type;
        using arg1 = std::tuple_element_t<0, signature::argument_type>;
        using arg2 = std::tuple_element_t<1, signature::argument_type>;
    
        static_assert(std::is_same{}, "!");
        static_assert(std::is_same{}, "!");
        static_assert(std::is_same{}, "!");
    }
    

    0 讨论(0)
提交回复
热议问题