【问题标题】:Why C++ Concepts return type requirement be a type-constraint and not also Primitive type?为什么 C++ 概念返回类型要求是类型约束而不是原始类型?
【发布时间】:2020-07-24 19:04:40
【问题描述】:

大家好,概念现在是 C++20 标准的一部分,为了使用它,我基本上写了这个我以前看到的示例

#include<iostream>

template<typename T>
concept Container= requires (T a){

    { a.size() } -> size_t;
    // others
}

template<Container Holder>
class Demo{};
int main(){


    Demo<std::vector<int>> d;


}

但在编译代码时出现以下错误

错误:return-type-requirement 不是类型约束 ({ a.size() } -> size_t;)

后来我记得返回类型约束不能是原始类型,并用 std::same_as 更改了代码

#include<iostream>

template<typename T>
concept Container= requires (T a){

    { a.size() } -> std::same_as<size_t>;
    // others
}

template<Container Holder>
class Demo{};
int main(){

    Demo<std::vector<int>> d;

}

其中 std::same_as 本身就是一个概念。

但是为什么不能使用原始类型呢?我知道它破坏了 C++ 中的某些内容,但我不记得了。

【问题讨论】:

  • -&gt; 右侧的表达式必须是“类型约束”。 std::same_as 是一个类型常量。 size_t 不是。你问为什么设计是这样的?因为那可能是题外话。
  • 是的,我想知道为什么它是这样设计的。我记得以前允许使用原始类型的语法,但它干扰了 C++ 中的某些功能(据我所知)
  • 旧语法是否破坏了某些代码?任何参考资料或示例都会很有帮助
  • 语言设计考古学通常不太适合这个网站,但也许有人会挖掘它。
  • 你可能会想到wg21.link/p1452

标签: c++ c++11 c++20


【解决方案1】:

因为语义不明确:{ a.size() } -&gt; size_t 是否意味着a.size() 的结果可转换为 size_t,或者decltype(a.size()) 完全 @ 987654325@?

因此,必须使用约束来明确意图(convertible_to 用于前者,same_as 用于后者)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    相关资源
    最近更新 更多