如果您有 C++11,则可以使用以下方法执行此操作:
#include <functional>
#include <utility>
#include <type_traits>
struct noncopyable_but_still_moveable {
noncopyable_but_still_moveable(const noncopyable_but_still_moveable&) = delete;
noncopyable_but_still_moveable(noncopyable_but_still_moveable&&) = default;
noncopyable_but_still_moveable() = default;
noncopyable_but_still_moveable& operator=(const noncopyable_but_still_moveable&) = default;
noncopyable_but_still_moveable& operator=(noncopyable_but_still_moveable&&) = default;
};
template <typename T>
struct test : noncopyable_but_still_moveable {
test(T) {}
// the rest is irrelevant
};
template <typename T>
test<T> make_test(T&& val) {
return test<typename std::remove_reference<T>::type>(std::forward<T>(val));
}
int main() {
auto && w = make_test(0);
}
请注意,我已替换boost::noncopyable
为具有已删除复制构造函数的类型。这是使某些东西不可复制的 C++11 方法,并且是必需的,因为 boost 类也是不可移动的。当然,您可以将其放在类本身中,不再继承。
如果没有 C++11,您将需要使用Boost move之类的东西来模拟这些语义。