【问题标题】:Why is the C++20 concept not compatible with "const auto&"?为什么 C++20 概念与“const auto&”不兼容?
【发布时间】:2021-07-30 01:17:01
【问题描述】:
template<typename T>
concept Octet = 1 == sizeof(T);

// ok
Octet decltype(auto) c = 'a';

// ok
void f1(const auto&) {}

// ok
void f2(Octet auto) {}

// ok
void f3(Octet auto&&) {}

// error: expected ‘auto’ or ‘decltype(auto)’ after ‘Octet’
void f4(Octet const auto&) {}

// error: cannot declare a parameter with ‘decltype(auto)’
void f5(Octet decltype(auto)) {}

使用gcc-11 -std=c++20 编译。见:https://godbolt.org/z/xK769Pfjn

为什么 f4 f5 不起作用?

【问题讨论】:

  • 嗯,语言终于强制执行正确的 const 了吗? ??????
  • Octet auto 表示类型。你可以有右常量或左常量,但不能有“中间常量”。
  • 为什么f5 不起作用? @DrewDormann
  • 包括所有必要的消息。 @largest_prime_is_463035818
  • @xmllmx f5 不是有效的 C++ 语法。它没有任何意义。您或许可以查看this question 以了解decltype(auto) 在C++ 中的含义。或者你可以edit这个问题来描述你认为该参数的含义。

标签: c++ templates c++20 c++-concepts type-deduction


【解决方案1】:

[dcl.spec.auto] 中所见,当您在此处使用占位符时,约束需要紧跟在auto 之前:

占位符类型说明符:
类型约束_选择 auto
类型约束_opt decltype ( auto )

这只是语法问题。约束不是像const 这样的通用说明符;它没有灵活的位置。从概念上讲,您可以将Octet auto 视为一个表示受限类型的“单词”。

至于f5,这是不允许作为每个p2的参数的:

“type-constraint_opt 形式的占位符类型说明符 auto" 可以用作函数声明的参数声明的 decl-specifier-seq 的 decl-specifier...

decltype(auto) 不存在此类文本。另外,根据p6:

在本子条款未明确允许的上下文中使用占位符类型的程序是格式错误的。

从逻辑上讲,我不确定如何指定 decltype(auto) 在这种情况下工作。当然,它可以被指定,但我认为语言中没有先例,因此需要对已经具有预期效果的替代方案进行激励。

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    相关资源
    最近更新 更多