Sunshine/sunshine/move_by_copy.h

52 lines
1.1 KiB
C
Raw Normal View History

2019-12-22 22:34:12 +00:00
#ifndef DOSSIER_MOVE_BY_COPY_H
#define DOSSIER_MOVE_BY_COPY_H
#include <utility>
namespace util {
/*
* When a copy is made, it moves the object
* This allows you to move an object when a move can't be done.
*/
template<class T>
class MoveByCopy {
public:
typedef T move_type;
2021-05-17 19:21:57 +00:00
2019-12-22 22:34:12 +00:00
private:
move_type _to_move;
2021-05-17 19:21:57 +00:00
public:
explicit MoveByCopy(move_type &&to_move) : _to_move(std::move(to_move)) {}
2019-12-22 22:34:12 +00:00
MoveByCopy(MoveByCopy &&other) = default;
2021-05-17 19:21:57 +00:00
2019-12-22 22:34:12 +00:00
MoveByCopy(const MoveByCopy &other) {
*this = other;
}
2021-05-17 19:21:57 +00:00
MoveByCopy &operator=(MoveByCopy &&other) = default;
MoveByCopy &operator=(const MoveByCopy &other) {
this->_to_move = std::move(const_cast<MoveByCopy &>(other)._to_move);
2019-12-22 22:34:12 +00:00
return *this;
}
operator move_type() {
return std::move(_to_move);
}
};
template<class T>
MoveByCopy<T> cmove(T &movable) {
return MoveByCopy<T>(std::move(movable));
}
// Do NOT use this unless you are absolutely certain the object to be moved is no longer used by the caller
template<class T>
MoveByCopy<T> const_cmove(const T &movable) {
2021-05-17 19:21:57 +00:00
return MoveByCopy<T>(std::move(const_cast<T &>(movable)));
2019-12-22 22:34:12 +00:00
}
2021-05-17 19:21:57 +00:00
} // namespace util
2019-12-22 22:34:12 +00:00
#endif