fork(2) download
  1. #include <memory>
  2. #include <type_traits>
  3.  
  4. template<bool> struct copyable {};
  5. template<> struct copyable<false>
  6. {
  7. copyable() = default; // default constructible
  8. copyable(copyable const&) = delete; // but not copyable
  9. };
  10.  
  11. template<typename T>
  12. class Container : copyable<std::is_copy_constructible<T>::value> {
  13. T t;
  14. public:
  15. Container() = default;
  16.  
  17. Container(const Container& other) : t(other.t) {}
  18.  
  19. Container(Container&& other) : t(std::move(other.t)) {}
  20. };
  21.  
  22. static_assert(std::is_copy_constructible<Container<int>>::value, "Non-Copyable");
  23. static_assert(!std::is_copy_constructible<Container<std::unique_ptr<int>>>::value, "Copyable");
  24.  
  25. Container<std::unique_ptr<int>> makeNonCopyableContainer() {
  26. return Container<std::unique_ptr<int>>();
  27. }
  28.  
  29. int main () {
  30. Container<int> c1;
  31. Container<int> c2(c1);
  32. Container<std::unique_ptr<int>> c3;
  33. // This would generate compile error:
  34. // Container<std::unique_ptr<int>> c4(c3);
  35. Container<std::unique_ptr<int>> c5(makeNonCopyableContainer());
  36. return 0;
  37. }
Compilation error #stdin compilation error #stdout 0s 3336KB
stdin
Standard input is empty
compilation info
prog.cpp:23:1: error: static assertion failed: Copyable
 static_assert(!std::is_copy_constructible<Container<std::unique_ptr<int>>>::value, "Copyable");
 ^
stdout
Standard output is empty