fork download
  1. template <typename T>
  2. class smart_ptr
  3. {
  4. public:
  5. // ... removed other member functions for simplicity
  6. T* get() { return ptr; }
  7.  
  8. template <typename U>
  9. auto operator [](U u) const -> decltype((*get())[u])
  10. {
  11. return (*get())[u];
  12. }
  13.  
  14. template <typename U>
  15. auto operator [](U u) -> decltype((*get())[u])
  16. {
  17. return (*get())[u];
  18. }
  19.  
  20. /*
  21.   // These work fine:
  22.  
  23.   template <typename U>
  24.   int operator [](U u)
  25.   {
  26.   return (*get())[u];
  27.   }
  28.  
  29.   template <typename U>
  30.   int& operator [](U u)
  31.   {
  32.   return (*get())[u];
  33.   }
  34. */
  35. private:
  36. T* ptr;
  37. };
  38.  
  39. struct Test
  40. {
  41. };
  42.  
  43. struct Test2
  44. {
  45. int& operator [](int i) { return m_Val; }
  46. int operator [](int i) const { return m_Val; }
  47.  
  48. int m_Val;
  49. };
  50.  
  51. int main()
  52. {
  53. smart_ptr<Test> p1;
  54. smart_ptr<Test2> p2;
  55. p2[0] = 1;
  56. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function 'int main()':
prog.cpp:55:9: error: no match for 'operator[]' in 'p2[0]'
stdout
Standard output is empty