It is possible to access the underlying container without copying the data, but it requires a certain amount of evil. The container is exposed as a protected member, called c
, which allows shenanigans such as this:
template <typename T>
class Shenanigans : private stack<T>
{
public:
explicit Shenanigans(stack<T>& victim) : victim(victim)
{
swap(victim);
}
~Shenanigans()
{
swap(victim);
}
using stack<T>::c;
private:
stack<T>& victim;
};
int main()
{
stack<int> s;
s.push(42);
{
Shenanigans<int> sh(s);
// The deque is accessible as sh.c, but the stack is temporarily empty.
cout << "Size: " << s.size() << " Data: " << sh.c.front() << "
";
}
// The stack is restored.
cout << "Size: " << s.size() << " Data: " << s.top() << "
";
}
Of course a far, far better solution is to choose a container that meets your needs.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…