std::assignable_from
来自 cppreference.cn
< cpp | 概念 (concepts)
定义于头文件 <concepts> |
||
template< class LHS, class RHS > concept assignable_from = |
(C++20 起) | |
概念 assignable_from<LHS, RHS>
指定了类型和值类别由 RHS
指定的表达式可以赋值给类型由 LHS
指定的左值表达式。
目录 |
[编辑] 语义要求
给定
-
lhs
,一个左值,引用对象lcopy
,使得 decltype((lhs)) 是LHS
, -
rhs
,一个表达式,使得 decltype((rhs)) 是RHS
, -
rcopy
,一个与rhs
相等的不同对象,
assignable_from<LHS, RHS>
仅当满足以下条件时才成立:
- std::addressof(lhs = rhs) == std::addressof(lcopy) (即,赋值表达式产生一个引用左操作数的左值);
- 在评估 lhs = rhs 后
-
lhs
等于rcopy
,除非rhs
是引用lcopy
的非 const xvalue(即,赋值是自移动赋值), - 如果
rhs
是一个 glvalue- 如果它是一个非 const xvalue,它引用的对象处于有效但未指定的状态;
- 否则,它引用的对象未被修改;
-
[编辑] 相等性保持
标准库概念的 requires 表达式中声明的表达式必须是保持相等性的(除非另有说明)。
[编辑] 注记
赋值不必是一个全函数。特别是,如果将某个对象 x
赋值给另一个对象 y
可能导致 y
被修改,那么 x = y 很可能不在 =
的定义域内。这通常发生在右操作数直接或间接由左操作数拥有时(例如,带有基于节点的数据结构中节点的智能指针,或类似 std::vector<std::any> 的情况)。
[编辑] 示例
运行此代码
#include <atomic> #include <concepts> #include <string> int main() { // Normal basic usage, checks lvalue reference assignment static_assert(std::is_assignable_v<int&, int>); static_assert(std::assignable_from<int&, int>); static_assert(std::is_assignable_v<std::string&, std::string>); static_assert(std::assignable_from<std::string&, std::string>); // Fundamental types don't support assignment to an rvalue static_assert(!std::is_assignable_v<int, int>); static_assert(!std::assignable_from<int, int>); // std::assignable_from doesn't accept all valid assignment expressions: // rvalue reference assignment static_assert(std::is_assignable_v<std::string&&, std::string>); static_assert(!std::assignable_from<std::string&&, std::string>); // rvalue assignment static_assert(std::is_assignable_v<std::string, std::string>); static_assert(!std::assignable_from<std::string, std::string>); // std::atomic::operator= returns by value static_assert(std::is_assignable_v<std::atomic<int>&, int>); static_assert(!std::assignable_from<std::atomic<int>&, int>); }
[编辑] 参考文献
- C++23 标准 (ISO/IEC 14882:2024)
- 18.4.8 概念
assignable_from
[concept.assignable]
- 18.4.8 概念
- C++20 标准 (ISO/IEC 14882:2020)
- 18.4.8 概念
assignable_from
[concept.assignable]
- 18.4.8 概念
[编辑] 参阅
(C++11)(C++11)(C++11) |
检查类型是否具有针对特定参数的赋值运算符 (类模板) |