名前空間
変種
操作

std::assignable_from

From cppreference.com
< cpp‎ | concepts
 
 
 
ヘッダ <concepts> で定義
template< class LHS, class RHS >

concept assignable_from =
    std::is_lvalue_reference_v<LHS> &&
    std::common_reference_with<
        const std::remove_reference_t<LHS>&,
        const std::remove_reference_t<RHS>&> &&
    requires(LHS lhs, RHS&& rhs) {
        { lhs = std::forward<RHS>(rhs) } -> std::same_as<LHS>;

    };
(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` が変更される可能性がある場合、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]
  • C++20 standard (ISO/IEC 14882:2020)
  • 18.4.8 コンセプト `assignable_from` [concept.assignable]

[編集] 関連項目

型が特定の引数に対する代入演算子を持つかをチェックする
(クラステンプレート) [編集]
English 日本語 中文(简体) 中文(繁體)