1

我发现trailing return type定义返回复杂类型的函数的返回非常容易,例如:

auto get_diag(int(&ar)[3][3])->int(&)[3]{ // using trailing return type
    static int diag[3]{
        ar[0][0], ar[1][1], ar[2][2]
    };
    return diag;
}

auto& get_diag2(int(&ar)[3][3]){ // adding & auto because otherwise it converts the array to pointer
    static int diag[3]{
        ar[0][0], ar[1][1], ar[2][2]
    };
    return diag;
}

int main(){

    int a[][3]{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    decltype(get_diag(a)) diag{
        get_diag(a)
    };

    for (auto i : diag)
        std::cout << i << ", ";
    std::cout << std::endl;

    decltype(get_diag2(a)) diag2{
        get_diag2(a)
    };

    for (auto i : diag2)
        std::cout << i << ", ";
    std::cout << std::endl;


    std::cout << std::endl;
}
  • 我想知道函数get_diagget_diag2. 所以只要输出相同,为什么我需要使用尾随返回类型?
4

1 回答 1

8
auto& get_diag2(int(&ar)[3][3]){ // adding & auto because otherwise it converts the array to pointer
    static int diag[3]{
        ar[0][0], ar[1][1], ar[2][2]
    };
    return diag;
}

不适用于 C++11 编译器。不带尾随返回类型的使用auto已添加到 C++14 中,其作用类似于将其用于变量时的 auto 工作方式。这意味着它永远不会返回引用类型,因此您必须使用auto&来返回对要返回的事物的引用。

如果您不知道应该返回引用还是值(这在泛型编程中经常发生),那么您可以将decltyp(auto)其用作返回类型。例如

template<class F, class... Args>
decltype(auto) Example(F func, Args&&... args) 
{ 
    return func(std::forward<Args>(args)...); 
}

如果func按值返回,则按值返回,如果func返回引用,则按引用返回。


简而言之,如果您使用 C++11,则必须指定返回类型,无论是在前面还是作为尾随返回类型。在 C++14 及更高版本中,您只需使用auto/decltype(auto)并让编译器为您处理它。

于 2019-04-18T20:19:34.570 回答