Reputation: 496
Let's say I have a stack which holds shared pointers for int
like following:
#include <stack>
#include <memory>
using namespace std;
int main()
{
stack<shared_ptr<int>> s1;
stack<shared_ptr<int>> s2;
shared_ptr<int> v1 = make_shared<int>(1);
shared_ptr<int> v2 = make_shared<int>(1);
s1.push(v1);
s2.push(v2);
bool areEqual = s1 == s2; // This is false
}
How do I make the stacks compare the actual values pointed to by the shared_ptr
and not the pointers themselves?
Upvotes: 3
Views: 292
Reputation: 170065
I like @RealFresh's answer. It demonstrates exactly how "encapsulating" protected accessibility really is. But casting a base class sub-object reference to a derived class sub-object reference and then treating it as one can quickly lead to undefined behavior.
The idea of extracting the c
member is however sound. We can do it without risk of UB with a simple utility:
template<class S>
constexpr decltype(auto) stack_c(S&& s) {
using base = std::decay_t<S>;
struct extractor : base {
using base::c;
};
constexpr auto c_ptr = &extractor::c;
return std::forward<S>(s).*c_ptr;
}
Due to how the expression &extractor::c
works, we obtain in fact a pointer to a member of base
(a std::stack
specialization), named c
. The purpose of extractor
is to make the name publicly accessible via a using declaration.
Then we forward back a reference to it, value category preserved and all. It's a drop in replacement in @RealFresh's suggestion to use std::equal
:
bool areEqual = std::equal(
stack_c(s1).begin(), stack_c(s1).end(),
stack_c(s2).begin(), stack_c(s2).end(),
[](auto const& p1, auto const& p2) {
return first && second && (p1 == p2 || *p1 == *p2);
}
);
Upvotes: 3
Reputation: 863
The std::stack
has a protected member c
which is an instance of the underlying container type. You can make a stack wrapper which accesses that variable, and then compare the contents of the underlying containers as follows:
#include <iostream>
#include <stack>
#include <memory>
#include <algorithm>
using namespace std;
template<class stack_type>
struct stack_wrapper : stack_type
{
auto begin() const
{
return stack_type::c.begin();
}
auto end() const
{
return stack_type::c.end();
}
};
template<class stack_type>
const stack_wrapper<stack_type> &wrap(const stack_type &stack)
{
return static_cast<const stack_wrapper<stack_type> &>(stack);
}
int main() {
stack<shared_ptr<int>> s1;
stack<shared_ptr<int>> s2;
shared_ptr<int> v1 = make_shared<int>(1);
shared_ptr<int> v2 = make_shared<int>(1);
s1.push(v1);
s2.push(v2);
const auto &s1wrapper = wrap(s1);
const auto &s2wrapper = wrap(s2);
const auto is_equal = std::equal(s1wrapper.begin(),
s1wrapper.end(),
s2wrapper.begin(),
s2wrapper.end(),
[](auto &first, auto &second) {
return first && second && *first == *second;
});
std::cout << is_equal << std::endl;
}
Upvotes: 4