我可以使用auto或decltype代替尾随返回类型吗?

时间:2019-04-18 19:59:58

标签: c++ c++11 auto trailing-return-type

我发现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之间的区别是什么。因此,只要输出相同,为什么我需要使用尾随返回类型?

1 个答案:

答案 0 :(得分: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编译器中将不起作用。在C ++ 14中添加了不带尾随返回类型的auto用法,其行为类似于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)并让编译器为您处理。

相关问题