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

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

In a comparison operator:

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


        
6条回答
  •  佛祖请我去吃肉
    2020-11-30 05:06

    template struct Derived_from {
     static void constraints(T* p) { B* pb = p; }
     Derived_from() { void(*p)(T*) = constraints; }
    };
    
    template
    bool test(R1& r1) {
     Derived_from(); // accept if R1 is derived from R2
     return false;
    }
    
    class Base {
    public:
     virtual ~Base() { }
    };
    
    class Derived : public Base {
    
    };
    
    class Other {
    
    };
    
    int _tmain(int argc, _TCHAR* argv[])
    {
     Derived d;
     Other o;
    
     test(d); // OK
     test(o); // Fails in VC++ 2005
    
     return 0;
    }
    

    Credits go to http://www2.research.att.com/~bs/bs_faq2.html#constraints

提交回复
热议问题