尾随 return 类型的非模板函数

Trailing return type in non-template functions

我见过有人使用以下语法来实现功能:

auto get_next() -> int 
{
   /// ...
}

而不是:

int get_next()
{
   /// ...
}

我都理解,而且我知道尾部 return 类型语法对于使用 decltype 的模板代码很有用。就个人而言,我会避免其他代码使用该语法,因为在阅读代码时,我更喜欢首先阅读函数的具体 return 类型,而不是最后。

如上所示,对非模板代码使用尾部 return 类型语法是否有任何优势(个人喜好或风格除外)?

好吧,您已经提到了尾随 return 类型的主要用例。如果 return 类型取决于参数,则使用它。 如果我们排除该用例,您可能获得的唯一优势是增强代码的可读性,特别是如果您的 return 类型有点复杂,但您没有使用尾随 [= 的技术优势12=] 在那种情况下。

一个潜在的好处是它使您声明的所有函数名称对齐:

auto get_next(int x, int y) -> int;
auto divide(double x, double y) -> double;
auto printSomething() -> void;
auto generateSubstring(const std::string &s, int start, int len) -> std::string;

来源:https://www.learncpp.com/cpp-tutorial/the-auto-keyword/

除了 之外,我可以想象有人可能喜欢 non-template 函数的尾随 return 类型:

  1. 为 lambda 表达式和函数指定 return 类型是相同的 w.r.t。语法。

  2. 当您阅读函数签名时left-to-right,函数参数在前。这可能更有意义,因为任何函数都需要参数来以 return 值的形式产生任何结果。

  3. 指定return类型时可以使用函数参数类型(反之无效):

    auto f(int x) -> decltype(x)
    {
        return x + 42;
    }
    

    这在上面的示例中没有意义,但请考虑长迭代器类型名称。