Restrict C++ Template Parameter to Subclass

前端 未结 7 1629
醉话见心
醉话见心 2020-11-28 22:04

How can I force a template parameter T to be a subclass of a specific class Baseclass? Something like this:

template 

        
7条回答
  •  醉酒成梦
    2020-11-28 22:36

    To execute less useless code at runtime you can look at: http://www.stroustrup.com/bs_faq2.html#constraints which provides some classes that perform the compile time test efficiently, and produce nicer error messages.

    In particular:

    template struct Derived_from {
            static void constraints(T* p) { B* pb = p; }
            Derived_from() { void(*p)(T*) = constraints; }
    };
    
    template void function() {
        Derived_from();
    }
    

提交回复
热议问题