fork download
  1. #include <iostream>
  2. using namespace std;
  3. template <typename T>
  4. class SmartPtr {
  5. public:
  6. SmartPtr(T* ptr = 0) : pointee(ptr) {}
  7. SmartPtr(SmartPtr& rhs) {
  8. pointee = rhs.pointee;
  9. rhs.pointee = 0;
  10. }
  11. SmartPtr<T>& operator=(SmartPtr<T>& rhs) {
  12. if(this == &rhs)
  13. return *this;
  14. pointee = rhs.pointee;
  15. rhs.pointee = 0;
  16. }
  17. ~SmartPtr() { delete pointee; }
  18. //operator->, etc. irrelevant here.
  19. //member template for type conversion
  20. template <typename NewType>
  21. operator SmartPtr<NewType>() {
  22. return SmartPtr<NewType>(pointee);
  23. }
  24. private:
  25. T* pointee;
  26. };
  27. class Remote {};
  28. class Base : public Remote {};
  29. class Derived : public Base {};
  30. void foo(const SmartPtr<Remote>& p) { cout << "remote" << endl;}
  31. void foo(const SmartPtr<Base>& p) { cout << "base" << endl;}
  32. template <>
  33. class SmartPtr<Base> {
  34. public:
  35. SmartPtr(Derived* p) : pointee(static_cast<Base*>(p)){}
  36. private:
  37. Base* pointee;
  38. };
  39. int main() {
  40. SmartPtr<Derived> d(new Derived());
  41. //foo(d); //ambiguous call. How to remove ambiguity?
  42. foo(static_cast<SmartPtr<Base>>(d)); //does not compile either.
  43. return 0;
  44. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
base