How to partially specialize a class template for all derived types?

前端 未结 2 1952
执笔经年
执笔经年 2021-01-04 13:27

I want to partially specialize an existing template that I cannot change (std::tr1::hash) for a base class and all derived classes. The reason is that I\'m usin

2条回答
  •  余生分开走
    2021-01-04 13:49

    There are two variants in the following code. You could choose more appropriated for you.

    
    template 
    struct CRTPBase
    {
        size_t hash() const {return 0; }
    };
    
    // First case 
    //
    // Help classes
    struct DummyF1 {};
    struct DummyF2 {};
    struct DummyF3 {};
    template struct X; 
    
    // Main classes
    template<> struct X : CRTPBase< X > {
        int a1;
    };
    
    template<> struct X : CRTPBase< X > {
        int b1;
    };
    
    // typedefs
    typedef X F1;
    typedef X F2;
    typedef DummyF3    F3; // Does not work
    
    namespace std { namespace tr1 {
        template
        struct hash< X > {
            size_t operator()(const CRTPBase< X > & base) const     
            {         
                return base.hash();     
            }
        };
    }} // namespace tr1 // namespace std 
    
    //
    
    // Second case
    struct DummyS1 : CRTPBase  {
        int m1;
    };
    //
    template 
    struct Y : T {};
    //
    typedef Y S1;
    
    
    namespace std { namespace tr1 {
        template
        struct hash< Y > {
            size_t operator()(const CRTPBase & base) const     
            {         
                return base.hash();     
            }
        };
    }} // namespace tr1 // namespace std 
    
    void main1()
    {
        using std::tr1::hash;
        F1 f1;
        F2 f2;
        F3 f3;
        hash hf1; size_t v1 = hf1(f1); // custom hash functor
        hash hf2; size_t v2 = hf2(f2); // custom hash functor
        hash hf3; size_t v3 = hf3(f3); // error: standard hash functor
    
        S1 s1;
        hash hs1; size_t w1 = hs1(s1); // custom hash functor
    
    }
    

提交回复
热议问题