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

前端 未结 2 1920
执笔经年
执笔经年 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条回答
  •  旧时难觅i
    2021-01-04 13:44

    Instead of modifying std::tr1::hash you should make your own namespace and define there new structure hash which inherited from std::tr1::hash or is specialized for CRTPBase.

    
    template 
    struct CRTPBase
    {
        size_t hash() {return 0; }
    };
    
    struct AA : CRTPBase  {};
    struct BB {};
    //
    namespace mynamespace {
    
    template  
    struct hash : std::tr1::hash {};
    //
    template 
    struct hash, Derived>, char>::type >
    {    
        size_t operator()(const CRTPBase & base) const     
        {         
            return base.hash();     
        }
    };
    
    } // namespace mynamespace {}
    //
    //
    void ff()
    {
        using namespace mynamespace;
    
        hash aa;  // my hash
        hash bb;  // std::tr1::hash
    
    }
    

提交回复
热议问题