I have a template class method
template
T pop();
Now I want to do a template specialization as follows,
You need a temporary proxy to dispatch to different results:
Example:
#include
#include
#include
class Stack
{
private:
std::vector m_data;
class Pop {
friend class Stack;
public:
Stack& stack;
Pop(Stack& stack)
: stack(stack)
{}
private:
Pop(const Pop&) = default;
Pop& operator = (const Pop&) = default;
public:
operator int () {
std::vector& data = stack.m_data;
int result = -1;
if( ! data.empty()) {
result = data.front();
data.erase(data.begin());
}
return result;
}
operator std::vector () {
std::vector& data = stack.m_data;
std::size_t size = std::min(data.size(), std::size_t(3));
std::vector result(data.begin(), data.begin() + size);
data.erase(data.begin(), data.begin() + size);
return result;
}
};
public:
Stack()
: m_data( {0, 1, 2, 3, 4, 5, 6, 7, 8} )
{}
const std::vector& data() const { return m_data; }
Pop pop() { return Pop(*this); }
};
int main()
{
Stack stack;
int i = stack.pop();
std::vector v = stack.pop();
std::cout << "i = " << i << '\n';
std::cout << "v = {";
for(auto i : v)
std::cout << i;
std::cout << "}\n";
}
Disclaimer: I consider the code totally useless (It might become useful if there is a pop() just returning a single value and a pop(std::size_t) converting to different containers, where the destructor of Pop is doing the erase).