Why is std::is_assignable counter-intuitive?

前端 未结 3 679

std::is_assignable::value == false in a conforming implementation (e.g. clang/libc++, gcc/libstdc++, but not VS2012).

Intuitively, this

3条回答
  •  庸人自扰
    2021-01-02 01:30

    In these traits, and with T not being an lvalue reference type, T implies an rvalue.

    With many user-defined types T, it is perfectly reasonable to assign to rvalue types. And it is even very useful in some contexts:

    std::vector v(5);
    v[0] = true;
    

    In the above expression, v[0] is an rvalue which is getting assigned to. And if vector is a poor example, then the following new C++11 code does the same:

    #include 
    
    std::tuple
    do_something();
    
    int
    main()
    {
        int i, j;
        std::tie(i, j) = do_something();
    }
    

    Above, the result of do_something() is being assigned to an rvalue std::tuple. Assigning to rvalues is useful, and even common, though not done in the great majority of uses of assignment.

    So std::is_assignable allows for the determining the distinction between being able to assign to an rvalue and to an lvalue. If you need to know the difference, std::is_assignable can do the work for you.

    If you are dealing with a more common case, such as just trying to figure out if a type T is copy assignable or not, then use is_copy_assignable. This trait is literally defined in terms of is_assignable and forces the lhs to an lvalue:

    is_copy_assignable == is_assignable
    

    So std::is_copy_assignable::value will be true as expected.

    Use is_copy_assignable as your first choice, or is_move_assignable if you need that too. Only when those traits don't work for you (perhaps because you need to look at a heterogeneous assignment), should you revert to using is_assignable directly. And then you need to deal with the question of whether or not you want to allow rvalues on the lhs so as to account for cases that might involve a vector::reference, or a tuple of references. You will have to explicitly choose whether or not you want to allow such cases in your is_assignable query.

    For example:

    #include 
    #include 
    
    int
    main()
    {
        static_assert(std::is_assignable::reference&, bool>(),
            "Should be able to assign a bool to an lvalue vector::reference");
    
        static_assert(std::is_assignable::reference, bool>(),
            "Should be able to assign a bool to an rvalue vector::reference");
    
        static_assert(std::is_assignable::reference>(),
            "Should be able to assign a vector::reference to an lvalue bool");
    
        static_assert(!std::is_assignable::reference>(),
            "Should not be able to assign a vector::reference to an rvalue bool");
    }
    

提交回复
热议问题