【问题标题】:Can i use auto or decltype instead trailing return type?我可以使用 auto 或 decltype 代替尾随返回类型吗?
【发布时间】:2019-09-09 04:51:48
【问题描述】:

我发现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这两个函数有什么区别。所以只要输出相同,为什么我需要使用尾随返回类型?

【问题讨论】:

  • get_diag2 不应编译,除非您使用 C++14 或更高版本。你确定你是用 C++11 编译的吗?
  • @NathanOliver:是的,你是真的。当我在 C++11 编译器上尝试它时,它无法抱怨:`'auto' return without trailing return type;推导的返回类型是 C++14 扩展。请添加它作为答案,以便它可能对其他 OPs 有用。

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


【解决方案1】:
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&amp; 来返回对您要返回的事物的引用。

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

【讨论】:

    猜你喜欢
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 2023-03-04
    • 2017-10-08
    • 2017-01-25
    • 2019-01-26
    • 1970-01-01
    相关资源
    最近更新 更多