C ++模板部分专门化 - 仅专门处理一个成员函数 [英] C++ template partial specialization - specializing one member function only

查看:121
本文介绍了C ++模板部分专门化 - 仅专门处理一个成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

碰到另一个模板问题:

问题:我想部分专门化一个容器类(foo)的情况下,对象是指针,想专门只有delete-method。应如下所示:

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:

lib代码

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的方法。
为什么?

This results into the compiler telling me that myptrs doesnt have a method called addSome. Why ?

Thanx。


/ strong> >基于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..."); } };
};

此解决方案根据核心问题#727


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

专业只有部分类。在你的情况下,最好的方法是重载函数 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 ++模板部分专门化 - 仅专门处理一个成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆