我可以使用auto或decltype而不是尾随返回类型吗?

问题描述 投票:4回答: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函数之间的区别。那么只要输出相同,为什么我需要使用尾随返回类型?
c++ c++11 auto trailing-return-type
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&返回对要返回的事物的引用。

如果您不知道是否应该返回引用或值(这在泛型编程中会发生很多),那么您可以使用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)并让编译器为您处理它。

© www.soinside.com 2019 - 2024. All rights reserved.