Search code examples
c++c++11type-traits

Type trait for moveable types?


I'm trying to write a template that behaves one way if T has a move constructor, and another way if T does not. I tried to look for a type trait that could identify this but have had no such luck and my attempts at writing my own type trait for this have failed.

Any help appreciated.


Solution

  • I feel the need to point out a subtle distinction.

    While <type_traits> does provide std::is_move_constructible and std::is_move_assignable, those do not exactly detect whether a type has a move constructor (resp. move assignment operator) or not. For instance, std::is_move_constructible<int>::value is true, and consider as well the following case:

    struct copy_only {
        copy_only(copy_only const&) {} // note: not defaulted on first declaration
    };
    static_assert( std::is_move_constructible<copy_only>::value
                 , "This won't trip" );
    

    Note that the user-declared copy constructor suppresses the implicit declaration of the move constructor: there is not even a hidden, compiler-generated copy_only(copy_only&&).

    The purpose of type traits is to facilitate generic programming, and are thus specified in terms of expressions (for want of concepts). std::is_move_constructible<T>::value is asking the question: is e.g. T t = T{}; valid? It is not asking (assuming T is a class type here) whether there is a T(T&&) (or any other valid form) move constructor declared.

    I don't know what you're trying to do and I have no reason not to believe that std::is_move_constructible isn't suitable for your purposes however.