Template specialization based on inherit class

后端 未结 4 1916
忘掉有多难
忘掉有多难 2020-12-01 03:39

I want to make this specialized w/o changing main. Is it possible to specialize something based on its base class? I hope so.

-edit-

I\'ll have several class

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 04:24

    Well, the article in the answer above appeared in February 2002. While it works, today we know there are better ways. Alternatively, you can use enable_if:

    template
    struct enable_if {
      typedef T type;
    };
    
    template
    struct enable_if { };
    
    template
    struct is_same {
        static bool const value = false;
    };
    
    template
    struct is_same {
        static bool const value = true;
    };
    
    template                                 
    struct is_base_of {                                                       
        static D * create_d();                     
        static char (& chk(B *))[1]; 
        static char (& chk(...))[2];           
        static bool const value = sizeof chk(create_d()) == 1 &&  
                                  !is_same::value;
    };
    
    struct SomeTag { };
    struct InheritSomeTag : SomeTag { };
    
    template
    struct MyClass { /* T not derived from SomeTag */ };
    
    template
    struct MyClass::value>::type> {
        typedef int isSpecialized;
    };
    
    int main() {
        MyClass::isSpecialized test1;        /* ok */
        MyClass::isSpecialized test2; /* ok */
    }
    

提交回复
热议问题