Re: display stack
From: Siemel Naran (SiemelNaran_at_REMOVE.att.net)
Date: 03/31/04
- Next message: John Harrison: "Re: c[++] pointer question"
- Previous message: Serve Laurijssen: "Re: Challenging macro with default value"
- In reply to: Alf P. Steinbach: "Re: display stack"
- Next in thread: Alf P. Steinbach: "Re: display stack"
- Reply: Alf P. Steinbach: "Re: display stack"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 31 Mar 2004 06:46:52 GMT
"Alf P. Steinbach" <alfps@start.no> wrote in message
> * "Siemel Naran" <SiemelNaran@REMOVE.att.net> schriebt:
> > Class std::stack<T, Container> contains a protected member c of type
> > Container. Perhaps you could derive your own stack class from
std::stack
> > and write the print() member function? In this form it would mean
deriving
> > publicly from a class with no virtual destructor, though you could use
> > private/protected inheritance with a lot of using declarations.
>
> Amazing. I saw that in the code but it wasn't documented in MSDN Lib.
But
> now when I read your posting I looked it up in the Holy Standard, and YES.
>
> So a more efficient version of the code I posted, which incidentally
> displays the elements in reverse order of the original code, is:
>
>
> #include <iostream>
> #include <stack>
>
>
> typedef std::stack<int> Stack;
>
> struct Hack: public Stack
> {
> typedef Stack::container_type Container;
> typedef Container::const_iterator ConstIterator;
> static Container const& containerOf( Stack const& s )
> {
> return static_cast<Hack const*>(&s)->c;
> }
> };
The containerOf function is unsound as the Stack may not originally be a
Hack.
Stack s;
Hack::containerOf(s); // invokes defined behavior, though in most compilers
nothing bad will happen
> void display( Stack const& aStack )
> {
> Hack::Container const& container = Hack::containerOf(
aStack );
> Hack::ConstIterator const end = container.end();
>
> for( Hack::ConstIterator it = container.begin(); it != end; ++it )
> {
> std::cout << *it << "\n";
> }
> }
> Now, logically this code should have undefined effect, but I'm not sure
> exactly where in the standard it says that.
In that part where static_cast from Base* to Derived* where the object is
not really a Derived* or higher class. It's in the static_cast section.
I think users should create an instance of Hack.
- Next message: John Harrison: "Re: c[++] pointer question"
- Previous message: Serve Laurijssen: "Re: Challenging macro with default value"
- In reply to: Alf P. Steinbach: "Re: display stack"
- Next in thread: Alf P. Steinbach: "Re: display stack"
- Reply: Alf P. Steinbach: "Re: display stack"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|