为什么 C++20 概念与“const auto&”不兼容?

时间:2021-05-07 18:14:06

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

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 不起作用?

1 个答案:

答案 0 :(得分:5)

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

<块引用>

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

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

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

<块引用>

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

decltype(auto) 不存在此类文本。此外,每个 p6:

<块引用>

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

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