【问题标题】:What is the purpose of a placeholder type in a trailing-return-type?尾随返回类型中占位符类型的目的是什么?
【发布时间】:2019-01-30 05:37:26
【问题描述】:

根据[dcl.fct]/2,下面的sn-p是合法的。 GCC and clang compile and execute the code,

#include <iostream>
int i = -1;
auto f()->auto&& { return i; }
int main(){
    f() = 2;
    std::cout << i << '\n';
}

打印

2

但是在 C++ 中允许这样做的目的是什么?

在上面的示例中,只需将 trailing-return-type 替换为 int&amp; 即可获得相同的结果。换句话说,我正在寻找一个包含占位符类型的尾随返回类型有意义的示例。

【问题讨论】:

  • 如果被禁止了,就会问“为什么禁止?”。
  • 为了让你在上面的代码中写f()这样的函数?
  • 为什么不允许?我不得不承认,我真的不明白
  • @user463035818 在上面的示例中,只需将 trailing-return-type 替换为 int&amp; 即可获得相同的结果。换句话说,我正在寻找一个包含占位符类型的尾随返回类型有意义的示例。
  • @WaldB:仅仅因为它没有真正的用途(?),它不应该被禁止。这会使语言不一致。

标签: c++ language-lawyer


【解决方案1】:

您可以就一致性提出一个论点:您可以将其他类型作为尾随返回类型,为什么不使用占位符?

auto f() -> int&  { return i; }
auto f() -> auto& { return i; }

你可以对实用程序提出一个论点:lambdas 的返回类型看起来像一个尾随返回类型,并且没有其他地方可以放置占位符类型,所以无论如何你必须允许它用于 lambdas,所以不妨允许它用于函数?

auto f = []() -> int&  { return i; };
auto f = []() -> auto& { return i; };

您可以就代码格式提出争论。尾随返回类型允许以一致的方式声明始终适用于所有情况的函数,因此只需将其排列起来:

auto g(auto x)     -> decltype(f(x)) { ... } // using trailing for parameter
auto Cls::member() -> type { ... }  // using trailing for scope (to find Cls::type)
auto h(auto x)     -> auto& { ... }  // using trailing for formatting

可能还有其他论点。但简而言之,它很容易允许并且显然具有优点。

【讨论】:

  • 你能解释一下auto g(auto x) -&gt; decltype(f(x)) { ... } // using trailing for argument是什么意思吗?这对我来说没有多大意义。
  • @WaldB 返回类型是根据参数(写参数,意思是参数),x,所以我需要放在尾随位置
  • 我不熟悉使用auto 作为参数类型。你能告诉我支持这一点的标准中的引用吗?
  • @WaldB 参数类型真的无所谓,我用auto作为简写。想象一个模板参数或其他什么。虽然 C++20 也将允许 auto
【解决方案2】:

您可以在auto的原始提案的修订版N3582 (2013-03-15)1中找到答案:

auto in trailing-return-type

该提案最初不允许在 trailing-return-type 中使用 auto,但此后有人指出,将其放在那里是指定 lambda 通过推导引用返回的唯一方法类型:

[]()->auto& { return f(); }

(请记住,不仅函数,lambda 也可以有 trailing-return-type

因此[dcl.spec.auto]/2:

auto type-specifier 可能与带有 trailing-return-type ([dcl.fct]) 的函数声明符一起出现在这样的任何上下文中声明符有效。


1 注意:N3582 在实际采用之前已被N3638 取代。

【讨论】:

  • [dcl.spec.auto]/3 我们有这样的短语:Otherwise, the function declaration shall declare a function.。鉴于函数声明在第一种情况下也声明了一个函数,即当函数声明符包含尾随返回类型时,这个断言的意义何在?你能澄清一下吗?
  • 这是一种非常奇怪的方式来表示 auto 不允许在例如void f(auto (*)());。见core issue 1892。 (而且它不是 declaration 而是 declarator
猜你喜欢
  • 2014-08-07
  • 2019-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
相关资源
最近更新 更多