Advertisement
stgatilov

Conditionally remove method

Feb 25th, 2018
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. #include <type_traits>
  2. #include <memory>
  3.  
  4. struct dummy {};
  5.  
  6. template<class T> class Vector {
  7.     T arr[42];
  8.  
  9.     template<class X = void> inline void push_back_impl(const dummy &x) {}
  10.     template<class X = void> inline void push_back_impl(const T &x) {
  11.         //copy assignment is used here
  12.         arr[0] = x;
  13.     }
  14. public:
  15.     void push_back(typename std::conditional<std::is_copy_assignable<T>::value, const T&, dummy>::type x) {
  16.         push_back_impl(x);
  17.     }
  18. };
  19.  
  20. //explicit instantiations work properly
  21. template class Vector<int>;
  22. template class Vector<std::unique_ptr<int>>;
  23.  
  24. int main() {
  25.     //this is OK:
  26.     Vector<int> ww;
  27.     ww.push_back(5);
  28.  
  29.     Vector<std::unique_ptr<int>> vv;
  30.     //uncomment to get compile error:
  31. //    vv.push_back(std::unique_ptr<int>());
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement