C++ Template Virtual Function
Hi,
I have Class A and according to my requirements the implementation of
the class is fixed. Class A manages the setting/getting of values.
The values stored can be of type integer, unsigned integer, character,
unsigned character and std::strings. The available types can grow in
the future. I'm having trouble finding a manageable way of storing
values of different types with the ability of retrieving them. The
problem area is class B's getValue method. It can't be a virtual
template method of a non template class. So, how should I provide a
unified way for class A to get a list of all the stored values that
match the tag value being passed?
I don't need to have a class B and C. If there is a better way that
only has one class, it's okay. I do want to avoid just having a bunch
of switch statements that executes different code based on different
types. This is what I think is unmanageable as new type are required.
#include<list>
class B
{
private:
unsigned long m_Tag;
public:
B(unsigned long tag) : m_Tag(tag) {}
template<typename T>
virtual int getValue(std::list<T> &val) = 0;
}; // end of class B
template<typename T>
class C : public B
{
private:
T m_Value;
public:
C(unsigned long const& tag, T const& value) : B(tag) {
m_Value = value;
}
virtual int getValue(std::list<T> &val) {
val.push_back(m_Value);
}
}; // end of class C
class A
{
private:
std::list<B> m_Collection;
public:
template<typename T>
setTagValue(unsigned long tag, T const& value) {
m_Collection.push_back(C<T>(tag, value));
}
template<typename T>
getTagValue(unsigned long const tag, std::list<T> values) {
for(auto i = m_Collection.begin(); i != m_Collection.end(); i++) {
if(i->getTag() == tag) {
i->getValue(values);
}
}
}
}; // end of class A
int main (void)
{
A collection;
collection.setTagValue(2, "hello");
collection.setTagValue(3, static_cast<int>(3));
std::list<int> values;
collection.getTagValue(3, values);
};