Namespaces
Variants

std:: semiregular

From cppreference.net
定义于头文件 <concepts>
template < class T >
concept semiregular = std:: copyable < T > && std:: default_initializable < T > ;
(C++20 起)

semiregular 概念规定类型必须同时可复制且可默认构造。该概念由行为类似于内置类型(如 int )的类型所满足,但这些类型不需要支持使用 == 进行比较。

示例

#include <concepts>
#include <iostream>
template<std::semiregular T>
// 致谢 Alexander Stepanov
// concepts 是对 T 的要求
// 对 T 的要求:T 是 semiregular
// T a(b); 或 T a = b; => 拷贝构造函数
// T a; => 默认构造函数
// a = b; => 赋值操作
struct Single
{
    T value;
    // Single 的聚合初始化行为类似于以下构造函数:
    // explicit Single(const T& x) : value(x) {}
    // 隐式声明的特殊成员函数行为类似于以下定义,
    // 但它们可能具有额外属性:
    // Single(const Single& x) : value(x.value) {}
    // Single() {}
    // ~Single() {}
    // Single& operator=(const Single& x) { value = x.value; return *this; }
    // 比较运算符未定义;`semiregular` concept 不要求此运算符
    // bool operator==(Single const& other) const = delete;
};
void print(std::semiregular auto x)
{
    std::cout << x.value << '\n';
}
int main()
{
    Single<int> myInt1{4};      // 聚合初始化:myInt1.value = 4
    Single<int> myInt2(myInt1); // 拷贝构造函数
    Single<int> myInt3;         // 默认构造函数
    myInt3 = myInt2;            // 拷贝赋值运算符
//  myInt1 == myInt2;           // 错误:operator== 未定义
    print(myInt1); // 正常:Single<int> 是 `semiregular` 类型
    print(myInt2);
    print(myInt3);
}   // Single<int> 变量在此处被销毁

输出:

4
4
4

参考文献

  • C++23 标准 (ISO/IEC 14882:2024):
  • 18.6 对象概念 [concepts.object]
  • C++20 标准 (ISO/IEC 14882:2020):
  • 18.6 对象概念 [concepts.object]

参见

(C++20)
规定类型为 regular,即它同时满足 semiregular equality_comparable 要求
(概念)