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

Can i use auto or decltype instead trailing return type?

本文关键字:返回类型 decltype 可以使 我可以      更新时间:2023-10-16

我发现定义返回复杂类型的函数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的功能有什么区别。所以只要输出相同,为什么我需要使用尾随返回类型?
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),让编译器为您处理。