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
不行?
最佳答案
如 [dcl.spec.auto] 中所示,当您在此处使用占位符时,约束需要紧跟在 auto
之前:
placeholder-type-specifier:
type-constraint_optauto
type-constraint_optdecltype ( auto )
这只是语法问题。约束不是像
const
这样的通用说明符。是;它没有灵活的立场。从概念上讲,您可以想到 Octet auto
作为代表约束类型的一个“词”。至于
f5
,这不允许作为每个 p2 的参数:A placeholder-type-specifier of the form "type-constraint_opt
auto
" can be used as a decl-specifier of the decl-specifier-seq of a parameter-declaration of a function declaration...
decltype(auto)
不存在此类文本.此外,根据 p6:A program that uses a placeholder type in a context not explicitly allowed in this subclause is ill-formed.
从逻辑上讲,我不确定如何指定
decltype(auto)
在这种情况下工作。当然,它可以被指定,但我认为语言中没有先例,因此需要对已经具有预期效果的替代方案进行激励。
关于c++ - 为什么 C++20 概念与 "const auto&"不兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67439885/