C++: How to require that one template type is derived from the other

前端 未结 6 954
北恋
北恋 2020-11-30 04:42

In a comparison operator:

template
bool operator==(Manager m1, Manager m2) {
    return m1.internal_field == m2         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 05:04

    In this post I'm considering the problem of checking if a type exactly matches another, it's not exactly what is asked for, but it is simpler and I hope it can help to understand the applied template tricks.

    As done in boost, template specializations can be adopted for that task, in fact you can define a template struct containing operations on a given type, and use nested template structs for that operations. In our case:

    // Working on a specific type:
    template 
    struct is_type {
        // For all types T2!=T1 produce false:
        template 
        struct same_of { static const bool value = false; };
        // Specialization for type T2==T1 producing true:
        template <>
        struct same_of { static const bool value = true; };
    };
    

    Defining a macro allows to use it easily:

    #define is_type_same(T1,T2) (is_type::same_of::value)
    

    as follows:

    template
    bool operator==(Manager m1, Manager m2) {
        return is_type_same(R1,R2) && m1.internal_field == m2.internal_field;
    }
    

提交回复
热议问题