本文介绍了C ++模板部分专门化 - 仅专门处理一个成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
>基于tony的答案这里是完全可编译的东西

Solution based on tony's answer here the fully compilable stuff

lib >

lib

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


推荐答案

第二个解决方案(正确的一个)

Second solution (correct one)

template <typename T>
class foo
{
public:
    void addSome    (T o) { printf ("adding that object..."); }
    void deleteSome(T o) { deleteSomeHelper<T>()(o); }
protected:
    template<typename TX>
    struct deleteSomeHelper { void operator()(TX& o) { printf ("deleting that object..."); } };
    template<typename TX>
    struct deleteSomeHelper<TX*> { void operator()(TX*& o) { printf ("deleting that PTR to an object..."); } };
};

此解决方案根据。

第一(不正确)解决方案:(保持此为评论引用)

专业只有部分类。在你的情况下,最好的方法是重载函数 deleteSome 如下:

You cannot specialize only part of class. In your case the best way is to overload function deleteSome as follows:

template <typename T>
class foo
{
public:
    void addSome    (T o) { printf ("adding that object..."); }
    void deleteSome (T o) { printf ("deleting that object..."); }
    void deleteSome (T* o) { printf ("deleting that object..."); }
};

这篇关于C ++模板部分专门化 - 仅专门处理一个成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 18:50