title: overload array operator with templates and pointers
body: <p>The following code compiles (without warnings) on both clang++-2.9 and g++-4.6. However, the g++ binary Seg Faults, while the clang++ binary runs as intended.</p>
  
  <p>What is the proper way to access template class data members through pointers when overloading []?</p>
  
  <p>Here's the code:</p>
  
  <pre class="lang-c prettyprint-override"><code>#include &lt;iostream&gt;
  template &lt;typename T&gt;
      class A {
      private:
      T val1;
      T val2;
  
      public:
      T&amp; getVal1() { return val1; }
      void setVal1(T aVal) { val1 = aVal; }
      T&amp; getVal2() { return val2; }
      void setVal2(T aVal) { val2 = aVal; }
  };
  
  template &lt;typename T&gt;
      class B {
      private:
      A&lt;T&gt;* aPtr;
  
      public:
      A&lt;T&gt;* getAPtr() { return aPtr; }
      T&amp; operator[](const int&amp; key) {
      if(key == 0) { T&amp; res = getAPtr()-&gt;getVal1();
          return res; }
      else { T&amp; res = getAPtr()-&gt;getVal2();
          return res; }
      }
  };
  
  int main()
  {
      B&lt;int&gt; foo;
      foo[0] = 1;
      int x = foo[0];
      std::cout &lt;&lt; foo[0] &lt;&lt; " " &lt;&lt; x &lt;&lt; std::endl; // 1 1
  }
  </code></pre>