Simplest way to determine return type of function

后端 未结 3 733
温柔的废话
温柔的废话 2020-12-05 01:32

Given a very simple, but lengthy function, such as:

int foo(int a, int b, int c, int d) {
    return 1;
}

// using ReturnTypeOfFoo = ???

W

3条回答
  •  半阙折子戏
    2020-12-05 02:37

    You can leverage std::function here which will give you an alias for the functions return type. This does require C++17 support, since it relies on class template argument deduction, but it will work with any callable type:

    using ReturnTypeOfFoo = decltype(std::function{foo})::result_type;
    

    We can make this a little more generic like

    template
    using return_type_of_t = 
        typename decltype(std::function{std::declval()})::result_type;
    

    which then lets you use it like

    int foo(int a, int b, int c, int d) {
        return 1;
    }
    
    auto bar = [](){ return 1; };
    
    struct baz_ 
    { 
        double operator()(){ return 0; } 
    } baz;
    
    using ReturnTypeOfFoo = return_type_of_t;
    using ReturnTypeOfBar = return_type_of_t;
    using ReturnTypeOfBaz = return_type_of_t;
    

提交回复
热议问题