碰到另一个模板问题:
问题:对于对象是指针的情况,我想部分专门化一个容器类(foo),并且我只想专门化删除方法。应该是这样的:
库代码
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..."); }
};
用户代码
foo<myclass> myclasses;
foo<myclass*> myptrs;
myptrs.addSome (new myclass());
这导致编译器告诉我 myptrs 没有名为 addSome 的方法。为什么 ?
谢谢。
解决方案
基于托尼的回答here完全可编译的东西库
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..."); }
};
用户
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