Hi everybody,
Bumped into another templates problem:
The problem: I want to partially specialize a container-class (foo) for the case that the objects are pointers, and i want to specialize only the delete-method. Should look like this:
The lib code
template <typename T>
class foo
{
public:
void addSome (T o) { printf ("adding that object..."); }
void deleteSome (T o) { printf ("deleting that object..."); }
};
template <typename T>
class foo <T *>
{
public:
void deleteSome (T* o) { printf ("deleting that PTR to an object..."); }
};
The user code
foo<myclass> myclasses;
foo<myclass*> myptrs;
myptrs.addSome (new myclass());
This results into the compiler telling me that myptrs doesnt have a method called addSome. Why ?
Thanx.
Solution
based on tony's answer here the fully compilable stufflib
template <typename T>
class foobase
{
public:
void addSome (T o) { printf ("adding that object..."); }
void deleteSome (T o) { printf ("deleting that object..."); }
};
template <typename T>
class foo : public foobase<T>
{ };
template <typename T>
class foo<T *> : public foobase<T *>
{
public:
void deleteSome (T* o) { printf ("deleting that ptr to an object..."); }
};
user
foo<int> fi;
foo<int*> fpi;
int i = 13;
fi.addSome (12);
fpi.addSome (&i);
fpi.deleteSome (12); // compiler-error: doesnt work
fi.deleteSome (&i); // compiler-error: doesnt work
fi.deleteSome (12); // foobase::deleteSome called
fpi.deleteSome (&i); // foo<T*>::deleteSome called