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

后端 未结 5 1319
执念已碎
执念已碎 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:45

    I haven't seen this solution yet, using boost's enable_if, is_same and remove_pointer to get two functions in a class, without any inheritance or other cruft.

    See below for a version using only remove_pointer.

    #include 
    #include 
    #include 
    
    template 
    class foo
    {
    public:
        typedef typename boost::remove_pointer::type T_noptr;
    
        void addSome    (T o) { printf ("adding that object..."); }
    
        template
        void deleteSome (U o, typename boost::enable_if>::type* dummy = 0) { 
            printf ("deleting that object..."); 
        }
        template
        void deleteSome (U* o, typename boost::enable_if>::type* dummy = 0) { 
            printf ("deleting that PTR to that object..."); 
        }
    };
    

    A simplified version is:

    #include 
    #include 
    
    template 
    class foo
    {
    public:
        typedef typename boost::remove_pointer::type T_value;
    
        void addSome    (T o) { printf ("adding that object..."); }
    
        void deleteSome (T_value& o) { // need ref to avoid auto-conv of double->int
            printf ("deleting that object..."); 
        }
    
        void deleteSome (T_value* o) { 
            printf ("deleting that PTR to that object..."); 
        }
    };
    

    And it works on MSVC 9: (commented out lines that give errors, as they are incorrect, but good to have for testing)

    void main()
    {
       foo x;
       foo y;
    
       int a;
       float b;
    
       x.deleteSome(a);
       x.deleteSome(&a);
       //x.deleteSome(b); // doesn't compile, as it shouldn't
       //x.deleteSome(&b);
       y.deleteSome(a);
       y.deleteSome(&a);
       //y.deleteSome(b);
       //y.deleteSome(&b);
    }
    

提交回复
热议问题