c++ - 为什么 C++20 概念与 "const auto&"不兼容?

标签 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 不行?

最佳答案

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

placeholder-type-specifier:
type-constraint_opt auto
type-constraint_opt decltype ( 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/

相关文章:

c++ - Direct3D11 在哪里分配资源对象?

c++ - 编写一个使多个容器看起来像一个的迭代器

c++ - 共享 void 指针。为什么这行得通?

c++ - 使模板参数公开的简化方法?

javascript - 如何将变量从模板工具包文件传递到 javascript 文件?

c++ - 非类型模板参数的类型转换无效

c++ - 为什么立即函数在默认情况下不是 noexcept,为什么允许它们是 noexcept(false)?

c++ - 为什么 C++20 允许默认比较即使被删除也能编译?

c++ - cmake和netbeans可以玩得好吗?

c++ - 使用类模板需要模板参数列表?