C++ template partial specialization - specializing one member function only

后端 未结 5 1288
执念已碎
执念已碎 2020-12-28 21:16

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

5条回答
  •  有刺的猬
    2020-12-28 21:52

    Second solution (correct one)

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

    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:

    template 
    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..."); }
    };
    

提交回复
热议问题