std::assignable_from
來自 cppreference.com
< 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) |
檢查型別是否具有針對特定引數的賦值運算子 (類模板) |