Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c++ > #14746

Re: Treat vector of SubClass as vector of SuperClass

From Ian Collins <ian-news@hotmail.com>
Newsgroups comp.lang.c++
Subject Re: Treat vector of SubClass as vector of SuperClass
Date 2012-03-05 10:45 +1300
Message-ID <9ri637FadbU3@mid.individual.net> (permalink)
References <14817030.1224.1330892827650.JavaMail.geo-discussion-forums@vbgu10>

Show all headers | View raw


On 03/ 5/12 09:27 AM, Ed wrote:

[please try and wrap lines!]

<snip>

> So, the real problem I'm trying to solve is that I'm trying to write a chess rules engine. In my code, I have a representation of a chess board in a Board class of my own making. The representation in the Board class of the actual board is a member variable of this type:
> vector<vector<shared_ptr<Square>  >  >
> where Square is another class of my making. Square extends a virtual class, AsciiRenderable. AsciiRenderables are passed to an AsciiRendering framework which I intend to have print the representation of the board out on the terminal.
>
> In other words, I wish the framework to operate on things with this signature:
> vector<vector<shared_ptr<AsciiRenderable>  >  >
>
> and Ideally, I would like to have it believe that
> vector<vector<shared_ptr<Square>  >  >  ISA vector<vector<shared_ptr<AsciiRenderable>  >  >
>
> As I write this, I do realize that the ISA relationship there cannot be true because you can add elements to the latter that cannot be elements of the former (anything that is AsciiRenderable yet not a Square). But is there a simple way to achieve what I seek?

One solution would be to derive your vector classes privately form 
std::vector:

#include <vector>
#include <tr1/memory>

struct AsciiRenderable {};
struct Square : AsciiRenderable {};

typedef std::tr1::shared_ptr<AsciiRenderable> Ptr;
typedef std::tr1::shared_ptr<Square>          SquarePtr;

struct Vector : private std::vector<Ptr>
{
   using std::vector<Ptr>::push_back;
};

struct SquareVector : Vector {};

void f( Vector& );

int main() {
   SquareVector v;

   v.push_back(SquarePtr(new Square));

   f(v);
}

-- 
Ian Collins

Back to comp.lang.c++ | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Treat vector of SubClass as vector of SuperClass Ed <edmacdonald555@gmail.com> - 2012-03-04 12:27 -0800
  Re: Treat vector of SubClass as vector of SuperClass Ian Collins <ian-news@hotmail.com> - 2012-03-05 10:45 +1300
  Re: Treat vector of SubClass as vector of SuperClass Jorgen Grahn <grahn+nntp@snipabacken.se> - 2012-03-07 14:47 +0000

csiph-web