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
Another solution. Use the auxiliary function
deleteSomeHelp
.I haven't seen this solution yet, using boost's
enable_if
,is_same
andremove_pointer
to get two functions in a class, without any inheritance or other cruft.See below for a version using only
remove_pointer
.A simplified version is:
And it works on MSVC 9: (commented out lines that give errors, as they are incorrect, but good to have for testing)
Second solution (correct one)
This solution is valid according to Core Issue #727.
First (incorrect) solution: (kept this as comments refer to it)
You cannot specialize only part of class. In your case the best way is to overload function
deleteSome
as follows:Create base class for single function
deleteSome
Make partial specialization
Use your base class
You can use inheritance to get this to work :