title: Using interfaces in C++ with STL containers
body: <p>I have two structs that had methods in common, that are defined in an Interface (I can't change these):</p>
  
  <pre><code>struct Interface {
     virtual int Foo() = 0;
  };
  struct A : Interface {
    virtual int Foo() override;
    //A specific methods etc  
  };
  struct B : Interface {
    virtual int Foo() override;
    //B specific methods etc
  };
  </code></pre>
  
  <p>If there's a function that needs to take an Interface then it's pretty simple:
      //a member variable
      std::vector m_as;</p>
  
  <pre><code>int DoubleFoo( Interface&amp; obj ) {
    return obj.Foo() * 2;
  }
  
  DoubleFoo(m_as[0]);
  </code></pre>
  
  <p>However if there's a function that needs multiple Interface then it's not so simple:</p>
  
  <pre><code>int SumFoo( std::vector&lt;Interface&gt;&amp; objs ) {
    int sum = 0;
    for (auto&amp;&amp; obj : objs ) {
      sum += obj.Foo();
    }
    return sum;
  }
  </code></pre>
  
  <p>because if I have an existing (eg member) variable of <code>std::vector&lt;A&gt;</code> I can't simply do:</p>
  
  <pre><code>SumFoo(m_as);
  </code></pre>
  
  <p>Instead I have to either change SumFoo to <code>std::vector&lt;Interface*&gt;</code> and have to create a new vector of pointers that point to the elements in the original array.</p>
  
  <p>Or just cast it in the function call, which is quite ugly:</p>
  
  <pre><code>SumFoo((std::vector&lt;Interface&gt;&amp;)m_as);
  </code></pre>
  
  <p>How is it possible to easily/nicely use interfaces in C++, when it comes to something as simple as needing a vector of them?</p>
  
  <p>I understand why I can't pass a subclass to a function expecting it's base class by value because of object slicing etc. But why isn't the cast from <code>std::vector&lt;Derived&gt;*</code> to <code>std::vector&lt;Base&gt;*</code> implicit, when <code>Derived*</code> to <code>Base*</code> is?</p>
  
  <p>I guess the problem would be you could add a Base() to the vector whcih would cause problems in the calling code because it thinks it's a vector of Derived, but then you could just make the argument const, and Base is abstract anyway.</p>