Accept any kind of callable and also know argument type

后端 未结 2 1334
旧时难觅i
旧时难觅i 2020-12-14 09:08

I\'m not sure if it\'s possible, so that\'s what I want to find out.

I\'d like to create a function which accepts any kind of functor/callable object, but I want to

2条回答
  •  离开以前
    2020-12-14 10:02

    Here's an example that will work for most callables including functors and lambdas (although not for generic functors as @Yakk demonstrated in a comment on the question).

    The code can also be useful when determining return type and multiple arguments.

    template 
    struct func_traits : public func_traits {};
    
    template 
    struct func_traits {
        using result_type =  Ret;
    
        template 
        struct arg {
            using type = typename std::tuple_element>::type;
        };
    };
    
    template 
    void option(T&& t) {
        using traits = func_traits::type>;
    
        using return_t = typename traits::result_type;         // Return type.
        using arg0_t = typename traits::template arg<0>::type; // First arg type.
    
        // Output types.
        std::cout << "Return type: " << typeid(return_t).name() << std::endl;
        std::cout << "Argument type: " << typeid(arg0_t).name() << std::endl;
    }
    

    To add support for regular functions add a specialization e.g.

    template 
    struct func_traits { /* ... */ }
    

    More useful info: Is it possible to figure out the parameter type and return type of a lambda?

提交回复
热议问题